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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:235",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:240",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:241",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:323",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:324",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:335",
"rustc_hir_typeck::expr", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/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
1519 method_inputs.to_mut().insert(
1522 pos.checked_sub(1).expect("pos should always be greater than 0") as usize,
1523 ty,
1524 );
1525 }
1526
1527 let method_tuple_args_flag =
1528 TupleArgumentsFlag::with_fn_sig_kind(method.sig.fn_sig_kind, true);
1529
1530 self.check_argument_types(
1531 segment.ident.span,
1532 expr,
1533 &method_inputs,
1534 method.sig.output(),
1535 expected,
1536 args,
1537 method.sig.fn_sig_kind.c_variadic(),
1538 method_tuple_args_flag,
1539 SplatLoweringInfo::FnDef(method.def_id),
1540 Some(method.args),
1541 );
1542
1543 self.check_call_abi(method.sig.abi(), expr.span);
1544
1545 method.sig.output()
1546 }
1547 Err(error) => {
1548 let guar = self.report_method_error(expr.hir_id, rcvr_t, error, expected, false);
1549
1550 let err_inputs = self.err_args(args.len(), guar);
1551 let err_ty = Ty::new_error(self.tcx, guar);
1552
1553 self.check_argument_types(
1554 segment.ident.span,
1555 expr,
1556 &err_inputs,
1557 err_ty,
1558 NoExpectation,
1559 args,
1560 false,
1561 TupleArgumentsFlag::DontTupleArguments,
1562 SplatLoweringInfo::Error(guar),
1563 Some(GenericArgsRef::default()),
1564 );
1565
1566 err_ty
1567 }
1568 }
1569 }
1570
1571 fn check_expr_use(
1573 &self,
1574 used_expr: &'tcx hir::Expr<'tcx>,
1575 expected: Expectation<'tcx>,
1576 ) -> Ty<'tcx> {
1577 self.check_expr_with_expectation(used_expr, expected)
1578 }
1579
1580 fn check_expr_cast(
1581 &self,
1582 e: &'tcx hir::Expr<'tcx>,
1583 t: &'tcx hir::Ty<'tcx>,
1584 expr: &'tcx hir::Expr<'tcx>,
1585 ) -> Ty<'tcx> {
1586 let t_cast = self.lower_ty_saving_user_provided_ty(t);
1589 let t_cast = self.deeply_resolve_ignoring_regions(t_cast);
1590 let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
1591 let t_expr = self.deeply_resolve_ignoring_regions(t_expr);
1592
1593 if let Err(guar) = (t_expr, t_cast).error_reported() {
1595 Ty::new_error(self.tcx, guar)
1596 } else {
1597 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
1599 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
1600 Ok(cast_check) => {
1601 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:1601",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(1601u32),
::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!(
1602 "check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
1603 t_cast, t_expr, cast_check,
1604 );
1605 deferred_cast_checks.push(cast_check);
1606 t_cast
1607 }
1608 Err(guar) => Ty::new_error(self.tcx, guar),
1609 }
1610 }
1611 }
1612
1613 fn check_expr_unsafe_binder_cast(
1614 &self,
1615 span: Span,
1616 kind: ast::UnsafeBinderCastKind,
1617 inner_expr: &'tcx hir::Expr<'tcx>,
1618 hir_ty: Option<&'tcx hir::Ty<'tcx>>,
1619 expected: Expectation<'tcx>,
1620 ) -> Ty<'tcx> {
1621 match kind {
1622 ast::UnsafeBinderCastKind::Wrap => {
1623 let ascribed_ty =
1624 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1625 let expected_ty = expected.only_has_type(self);
1626 let binder_ty = match (ascribed_ty, expected_ty) {
1627 (Some(ascribed_ty), Some(expected_ty)) => {
1628 self.demand_eqtype(inner_expr.span, expected_ty, ascribed_ty);
1629 expected_ty
1630 }
1631 (Some(ty), None) | (None, Some(ty)) => ty,
1632 (None, None) => self.next_ty_var(inner_expr.span),
1636 };
1637
1638 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1639 let hint_ty = match *binder_ty.kind() {
1640 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1641 inner_expr.span,
1642 infer::BoundRegionConversionTime::HigherRankedType,
1643 binder.into(),
1644 ),
1645 ty::Error(e) => Ty::new_error(self.tcx, e),
1646 _ => {
1647 let guar = self
1648 .dcx()
1649 .struct_span_err(
1650 hir_ty.map_or(span, |hir_ty| hir_ty.span),
1651 ::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!(
1652 "`wrap_binder!()` can only wrap into unsafe binder, not {}",
1653 binder_ty.sort_string(self.tcx)
1654 ),
1655 )
1656 .with_note("unsafe binders are the only valid output of wrap")
1657 .emit_err();
1658 Ty::new_error(self.tcx, guar)
1659 }
1660 };
1661
1662 self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1663
1664 binder_ty
1665 }
1666 ast::UnsafeBinderCastKind::Unwrap => {
1667 let ascribed_ty =
1668 hir_ty.map(|hir_ty| self.lower_ty_saving_user_provided_ty(hir_ty));
1669 let hint_ty = ascribed_ty.unwrap_or_else(|| self.next_ty_var(inner_expr.span));
1670 let binder_ty = self.check_expr_has_type_or_error(inner_expr, hint_ty, |_| {});
1672
1673 let binder_ty = self.structurally_resolve_type(inner_expr.span, binder_ty);
1676 match *binder_ty.kind() {
1677 ty::UnsafeBinder(binder) => self.instantiate_binder_with_fresh_vars(
1678 inner_expr.span,
1679 infer::BoundRegionConversionTime::HigherRankedType,
1680 binder.into(),
1681 ),
1682 ty::Error(e) => Ty::new_error(self.tcx, e),
1683 _ => {
1684 let guar = self
1685 .dcx()
1686 .struct_span_err(
1687 hir_ty.map_or(inner_expr.span, |hir_ty| hir_ty.span),
1688 ::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!(
1689 "expected unsafe binder, found {} as input of \
1690 `unwrap_binder!()`",
1691 binder_ty.sort_string(self.tcx)
1692 ),
1693 )
1694 .with_note("only an unsafe binder type can be unwrapped")
1695 .emit_err();
1696 Ty::new_error(self.tcx, guar)
1697 }
1698 }
1699 }
1700 }
1701 }
1702
1703 fn check_expr_array(
1704 &self,
1705 args: &'tcx [hir::Expr<'tcx>],
1706 expected: Expectation<'tcx>,
1707 expr: &'tcx hir::Expr<'tcx>,
1708 ) -> Ty<'tcx> {
1709 let element_ty = if !args.is_empty() {
1710 let coerce_to = expected
1711 .to_option(self)
1712 .and_then(|uty| {
1713 self.deeply_resolve_ignoring_regions_with_obligations(uty)
1714 .builtin_index()
1715 .filter(|t| {
1718 !self.deeply_resolve_ignoring_regions_with_obligations(*t).is_ty_var()
1719 })
1720 })
1721 .unwrap_or_else(|| self.next_ty_var(expr.span));
1722 let mut coerce = CoerceMany::with_capacity(coerce_to, args.len());
1723
1724 for e in args {
1725 let e_ty = self.check_expr_with_hint(e, coerce_to);
1731 let cause = self.misc(e.span);
1732 coerce.coerce(self, &cause, e, e_ty);
1733 }
1734 coerce.complete(self)
1735 } else {
1736 self.next_ty_var(expr.span)
1737 };
1738 let array_len = args.len() as u64;
1739 Ty::new_array(self.tcx, element_ty, array_len)
1740 }
1741
1742 pub(super) fn check_expr_const_block(
1743 &self,
1744 block: &'tcx hir::ConstBlock,
1745 expected: Expectation<'tcx>,
1746 ) -> Ty<'tcx> {
1747 let body = self.tcx.hir_body(block.body);
1748
1749 let def_id = block.def_id;
1751 let fcx = FnCtxt::new(self, self.param_env, def_id);
1752
1753 let ty = fcx.check_expr_with_expectation(body.value, expected);
1754 fcx.require_type_is_sized(ty, body.value.span, ObligationCauseCode::SizedConstOrStatic);
1755 fcx.write_ty(block.hir_id, ty);
1756 ty
1757 }
1758
1759 fn check_expr_repeat(
1760 &self,
1761 element: &'tcx hir::Expr<'tcx>,
1762 count: &'tcx hir::ConstArg<'tcx>,
1763 expected: Expectation<'tcx>,
1764 expr: &'tcx hir::Expr<'tcx>,
1765 ) -> Ty<'tcx> {
1766 let tcx = self.tcx;
1767 let count_span = count.span;
1768 let count = self.try_structurally_resolve_const(
1769 count_span,
1770 self.normalize(
1771 count_span,
1772 Unnormalized::new_wip(self.lower_const_arg(count, tcx.types.usize)),
1773 ),
1774 );
1775
1776 let uty = match expected {
1777 ExpectHasType(uty) => uty.builtin_index(),
1778 _ => None,
1779 };
1780
1781 let (element_ty, t) = match uty {
1782 Some(uty) => {
1783 self.check_expr_coercible_to_type(element, uty, None);
1784 (uty, uty)
1785 }
1786 None => {
1787 let ty = self.next_ty_var(element.span);
1788 let element_ty = self.check_expr_has_type_or_error(element, ty, |_| {});
1789 (element_ty, ty)
1790 }
1791 };
1792
1793 if let Err(guar) = element_ty.error_reported() {
1794 return Ty::new_error(tcx, guar);
1795 }
1796
1797 self.deferred_repeat_expr_checks.borrow_mut().push((element, element_ty, count));
1801
1802 let ty = Ty::new_array_with_const_len(tcx, t, count);
1803 self.register_wf_obligation(
1804 ty.into(),
1805 expr.span,
1806 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(expr.hir_id)),
1807 );
1808 ty
1809 }
1810
1811 fn check_expr_tuple(
1812 &self,
1813 elements: &'tcx [hir::Expr<'tcx>],
1814 expected: Expectation<'tcx>,
1815 expr: &'tcx hir::Expr<'tcx>,
1816 ) -> Ty<'tcx> {
1817 let mut expectations = expected
1818 .only_has_type(self)
1819 .and_then(|ty| {
1820 self.deeply_resolve_ignoring_regions_with_obligations(ty).opt_tuple_fields()
1821 })
1822 .unwrap_or_default()
1823 .iter();
1824
1825 let elements = elements.iter().map(|e| {
1826 let ty = expectations.next().unwrap_or_else(|| self.next_ty_var(e.span));
1827 self.check_expr_coercible_to_type(e, ty, None);
1828 ty
1829 });
1830
1831 let tuple = Ty::new_tup_from_iter(self.tcx, elements);
1832
1833 if let Err(guar) = tuple.error_reported() {
1834 Ty::new_error(self.tcx, guar)
1835 } else {
1836 self.require_type_is_sized(
1837 tuple,
1838 expr.span,
1839 ObligationCauseCode::TupleInitializerSized,
1840 );
1841 tuple
1842 }
1843 }
1844
1845 fn check_expr_struct(
1846 &self,
1847 expr: &hir::Expr<'tcx>,
1848 expected: Expectation<'tcx>,
1849 qpath: &'tcx QPath<'tcx>,
1850 fields: &'tcx [hir::ExprField<'tcx>],
1851 base_expr: &'tcx hir::StructTailExpr<'tcx>,
1852 ) -> Ty<'tcx> {
1853 let (variant, adt_ty) = match self.check_struct_path(qpath, expr.hir_id) {
1855 Ok(data) => data,
1856 Err(guar) => {
1857 self.check_struct_fields_on_error(fields, base_expr);
1858 return Ty::new_error(self.tcx, guar);
1859 }
1860 };
1861
1862 let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
1864 if variant.field_list_has_applicable_non_exhaustive() {
1865 self.dcx()
1866 .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
1867 }
1868
1869 self.check_expr_struct_fields(
1870 adt_ty,
1871 expected,
1872 expr,
1873 qpath.span(),
1874 variant,
1875 fields,
1876 base_expr,
1877 );
1878
1879 self.require_type_is_sized(adt_ty, expr.span, ObligationCauseCode::StructInitializerSized);
1880 adt_ty
1881 }
1882
1883 fn check_expr_struct_fields(
1884 &self,
1885 adt_ty: Ty<'tcx>,
1886 expected: Expectation<'tcx>,
1887 expr: &hir::Expr<'_>,
1888 path_span: Span,
1889 variant: &'tcx ty::VariantDef,
1890 hir_fields: &'tcx [hir::ExprField<'tcx>],
1891 base_expr: &'tcx hir::StructTailExpr<'tcx>,
1892 ) {
1893 let tcx = self.tcx;
1894
1895 let adt_ty = self.deeply_resolve_ignoring_regions_with_obligations(adt_ty);
1896 let adt_ty_hint = expected.only_has_type(self).and_then(|expected| {
1897 self.fudge_inference_if_ok(|| {
1898 let ocx = ObligationCtxt::new(self);
1899 ocx.sup(&self.misc(path_span), self.param_env, expected, adt_ty)?;
1900 if !ocx.try_evaluate_obligations().no_errors() {
1901 return Err(TypeError::Mismatch);
1902 }
1903 Ok(self.deeply_resolve_ignoring_regions(adt_ty))
1904 })
1905 .ok()
1906 });
1907 if let Some(adt_ty_hint) = adt_ty_hint {
1908 self.demand_eqtype(path_span, adt_ty_hint, adt_ty);
1910 }
1911
1912 let ty::Adt(adt, args) = adt_ty.kind() else {
1913 ::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");
1914 };
1915 let adt_kind = adt.adt_kind();
1916
1917 let get_field_ident = |field: &ty::FieldDef| field.ident(tcx).normalize_to_macros_2_0();
1918 let mut remaining_fields = variant
1919 .fields
1920 .iter_enumerated()
1921 .map(|(i, field)| (get_field_ident(field), (i, field)))
1922 .collect::<UnordMap<_, _>>();
1923
1924 let mut seen_fields = FxHashMap::default();
1925
1926 let mut error_happened = false;
1927
1928 if variant.fields.len() != remaining_fields.len() {
1929 let guar =
1932 self.dcx().span_delayed_bug(expr.span, "struct fields have non-unique names");
1933 self.set_tainted_by_errors(guar);
1934 error_happened = true;
1935 }
1936
1937 for (idx, field) in hir_fields.iter().enumerate() {
1939 let ident = if field.ident.name == kw::Underscore {
1940 if let [v_field] = &variant.fields[..] {
1946 Ok(get_field_ident(v_field))
1947 } else {
1948 Err(tcx.dcx().span_delayed_bug(
1949 field.ident.span,
1950 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("can not infer the delegation `Self` mapping field for {0:?}",
self.body_def_id))
})format!(
1951 "can not infer the delegation `Self` mapping field for {:?}",
1952 self.body_def_id
1953 ),
1954 ))
1955 }
1956 } else {
1957 Ok(tcx.adjust_ident(field.ident, variant.def_id))
1958 };
1959
1960 let field_type = ident
1961 .and_then(|ident| {
1962 if let Some((i, v_field)) = remaining_fields.remove(&ident) {
1963 seen_fields.insert(ident, field.span);
1964 self.write_field_index(field.hir_id, i);
1965
1966 if adt_kind != AdtKind::Enum {
1970 tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None);
1971 }
1972
1973 Ok(self.field_ty(field.span, v_field, args))
1974 } else {
1975 error_happened = true;
1976 let guar = if let Some(prev_span) = seen_fields.get(&ident) {
1977 self.dcx().emit_err(FieldMultiplySpecifiedInInitializer {
1978 span: field.ident.span,
1979 prev_span: *prev_span,
1980 ident,
1981 })
1982 } else {
1983 self.report_unknown_field(
1984 adt_ty,
1985 variant,
1986 expr,
1987 field,
1988 hir_fields,
1989 adt.variant_descr(),
1990 )
1991 };
1992
1993 Err(guar)
1994 }
1995 })
1996 .unwrap_or_else(|err| Ty::new_error(tcx, err));
1997
1998 self.register_wf_obligation(
2002 field_type.into(),
2003 field.expr.span,
2004 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(field.expr.hir_id)),
2005 );
2006
2007 let ty = self.check_expr_with_hint(field.expr, field_type);
2010 let diag = self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
2011
2012 if let Err(diag) = diag {
2013 if idx == hir_fields.len() - 1 {
2014 if remaining_fields.is_empty() {
2015 self.suggest_fru_from_range_and_emit(field, variant, args, diag);
2016 } else {
2017 diag.stash(field.span, StashKey::MaybeFruTypo);
2018 }
2019 } else {
2020 diag.emit();
2021 }
2022 }
2023 }
2024
2025 if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
2027 {
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!(
2028 self.dcx(),
2029 path_span,
2030 E0784,
2031 "union expressions should have exactly one field",
2032 )
2033 .emit();
2034 }
2035
2036 if error_happened {
2040 if let hir::StructTailExpr::Base(base_expr) = base_expr {
2041 self.check_expr(base_expr);
2042 }
2043 return;
2044 }
2045
2046 match *base_expr {
2047 hir::StructTailExpr::DefaultFields(span) => {
2048 let mut missing_mandatory_fields = Vec::new();
2049 let mut missing_optional_fields = Vec::new();
2050 for f in &variant.fields {
2051 let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2052 if let Some(_) = remaining_fields.remove(&ident) {
2053 if f.value.is_none() {
2054 missing_mandatory_fields.push(ident);
2055 } else {
2056 missing_optional_fields.push(ident);
2057 }
2058 }
2059 }
2060 if !self.tcx.features().default_field_values() {
2061 let sugg = self.tcx.crate_level_attribute_injection_span();
2062 self.dcx().emit_err(BaseExpressionDoubleDot {
2063 span: span.shrink_to_hi(),
2064 default_field_values_suggestion: if self.tcx.sess.is_nightly_build()
2067 && missing_mandatory_fields.is_empty()
2068 && !missing_optional_fields.is_empty()
2069 {
2070 Some(sugg)
2071 } else {
2072 None
2073 },
2074 add_expr: if !missing_mandatory_fields.is_empty()
2075 || !missing_optional_fields.is_empty()
2076 {
2077 Some(BaseExpressionDoubleDotAddExpr { span: span.shrink_to_hi() })
2078 } else {
2079 None
2080 },
2081 remove_dots: if missing_mandatory_fields.is_empty()
2082 && missing_optional_fields.is_empty()
2083 {
2084 Some(BaseExpressionDoubleDotRemove { span })
2085 } else {
2086 None
2087 },
2088 });
2089 return;
2090 }
2091 if variant.fields.is_empty() {
2092 let mut err = self.dcx().struct_span_err(
2093 span,
2094 ::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!(
2095 "`{adt_ty}` has no fields, `..` needs at least one default field in \
2096 the struct definition",
2097 ),
2098 );
2099 err.span_label(path_span, "this type has no fields");
2100 err.emit();
2101 }
2102 if !missing_mandatory_fields.is_empty() {
2103 let s = if missing_mandatory_fields.len() == 1 { "" } else { "s" }pluralize!(missing_mandatory_fields.len());
2104 let fields = listify(&missing_mandatory_fields, |f| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", f))
})format!("`{f}`")).unwrap();
2105 self.dcx()
2106 .struct_span_err(
2107 span.shrink_to_lo(),
2108 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("missing field{0} {1} in initializer",
s, fields))
})format!("missing field{s} {fields} in initializer"),
2109 )
2110 .with_span_label(
2111 span.shrink_to_lo(),
2112 "fields that do not have a defaulted value must be provided explicitly",
2113 )
2114 .emit();
2115 return;
2116 }
2117 let fru_tys = match adt_ty.kind() {
2118 ty::Adt(adt, args) if adt.is_struct() => variant
2119 .fields
2120 .iter()
2121 .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2122 .collect(),
2123 ty::Adt(adt, args) if adt.is_enum() => variant
2124 .fields
2125 .iter()
2126 .map(|f| self.normalize(span, f.ty(self.tcx, args)))
2127 .collect(),
2128 _ => {
2129 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span });
2130 return;
2131 }
2132 };
2133 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2134 }
2135 hir::StructTailExpr::Base(base_expr) => {
2136 let fru_tys = if self.tcx.features().type_changing_struct_update() {
2139 if adt.is_struct() {
2140 let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did());
2142 let fru_tys = variant
2147 .fields
2148 .iter()
2149 .map(|f| {
2150 let fru_ty = self.normalize(
2151 expr.span,
2152 Unnormalized::new_wip(self.field_ty(
2153 base_expr.span,
2154 f,
2155 fresh_args,
2156 )),
2157 );
2158 let ident =
2159 self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
2160 if let Some(_) = remaining_fields.remove(&ident) {
2161 let target_ty = self.field_ty(base_expr.span, f, args);
2162 let cause = self.misc(base_expr.span);
2163 if let Err(diag) =
2164 self.demand_suptype_diag(cause.span, target_ty, fru_ty)
2165 {
2166 diag.delay_as_bug();
2167 }
2168 }
2169 self.deeply_resolve_ignoring_regions(fru_ty)
2170 })
2171 .collect();
2172 let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args);
2191 self.check_expr_has_type_or_error(
2192 base_expr,
2193 self.deeply_resolve_ignoring_regions(fresh_base_ty),
2194 |_| {},
2195 );
2196 fru_tys
2197 } else {
2198 self.check_expr(base_expr);
2201 self.dcx()
2202 .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
2203 return;
2204 }
2205 } else {
2206 self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
2207 let base_ty = self.typeck_results.borrow().expr_ty(base_expr);
2208 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()),
2209 (ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt);
2210 if self.tcx.sess.is_nightly_build() && same_adt {
2211 feature_err(
2212 &self.tcx.sess,
2213 sym::type_changing_struct_update,
2214 base_expr.span,
2215 "type changing struct updating is experimental",
2216 )
2217 .emit();
2218 }
2219 });
2220 match adt_ty.kind() {
2221 ty::Adt(adt, args) if adt.is_struct() => variant
2222 .fields
2223 .iter()
2224 .map(|f| self.normalize(expr.span, f.ty(self.tcx, args)))
2225 .collect(),
2226 _ => {
2227 self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct {
2228 span: base_expr.span,
2229 });
2230 return;
2231 }
2232 }
2233 };
2234 self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr.hir_id, fru_tys);
2235 }
2236 rustc_hir::StructTailExpr::NoneWithError(guaranteed) => {
2237 self.infcx.set_tainted_by_errors(guaranteed);
2248 }
2249 rustc_hir::StructTailExpr::None => {
2250 if adt_kind != AdtKind::Union
2251 && !remaining_fields.is_empty()
2252 && !variant.field_list_has_applicable_non_exhaustive()
2254 {
2255 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:2255",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2255u32),
::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);
2256
2257 let private_fields: Vec<&ty::FieldDef> = variant
2260 .fields
2261 .iter()
2262 .filter(|field| !field.vis.is_accessible_from(self.mod_id, tcx))
2263 .collect();
2264
2265 if !private_fields.is_empty() {
2266 self.report_private_fields(
2267 adt_ty,
2268 path_span,
2269 expr.span,
2270 private_fields,
2271 hir_fields,
2272 );
2273 } else {
2274 self.report_missing_fields(
2275 adt_ty,
2276 path_span,
2277 expr.span,
2278 remaining_fields,
2279 variant,
2280 hir_fields,
2281 args,
2282 );
2283 }
2284 }
2285 }
2286 }
2287 }
2288
2289 fn check_struct_fields_on_error(
2290 &self,
2291 fields: &'tcx [hir::ExprField<'tcx>],
2292 base_expr: &'tcx hir::StructTailExpr<'tcx>,
2293 ) {
2294 for field in fields {
2295 self.check_expr(field.expr);
2296 }
2297 if let hir::StructTailExpr::Base(base) = *base_expr {
2298 self.check_expr(base);
2299 }
2300 }
2301
2302 fn report_missing_fields(
2314 &self,
2315 adt_ty: Ty<'tcx>,
2316 span: Span,
2317 full_span: Span,
2318 remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
2319 variant: &'tcx ty::VariantDef,
2320 hir_fields: &'tcx [hir::ExprField<'tcx>],
2321 args: GenericArgsRef<'tcx>,
2322 ) {
2323 let len = remaining_fields.len();
2324
2325 let displayable_field_names: Vec<&str> =
2326 remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();
2327
2328 let mut truncated_fields_error = String::new();
2329 let remaining_fields_names = match &displayable_field_names[..] {
2330 [field1] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", field1))
})format!("`{field1}`"),
2331 [field1, field2] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and `{1}`", field1, field2))
})format!("`{field1}` and `{field2}`"),
2332 [field1, field2, field3] => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`, `{1}` and `{2}`", field1,
field2, field3))
})format!("`{field1}`, `{field2}` and `{field3}`"),
2333 _ => {
2334 truncated_fields_error =
2335 ::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));
2336 displayable_field_names
2337 .iter()
2338 .take(3)
2339 .map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`"))
2340 .collect::<Vec<_>>()
2341 .join(", ")
2342 }
2343 };
2344
2345 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!(
2346 self.dcx(),
2347 span,
2348 E0063,
2349 "missing field{} {}{} in initializer of `{}`",
2350 pluralize!(len),
2351 remaining_fields_names,
2352 truncated_fields_error,
2353 adt_ty
2354 );
2355 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}"));
2356
2357 if remaining_fields.items().all(|(_, (_, field))| field.value.is_some())
2358 && self.tcx.sess.is_nightly_build()
2359 {
2360 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!(
2361 "all remaining fields have default values, {you_can} use those values with `..`",
2362 you_can = if self.tcx.features().default_field_values() {
2363 "you can"
2364 } else {
2365 "if you added `#![feature(default_field_values)]` to your crate you could"
2366 },
2367 );
2368 if let Some(hir_field) = hir_fields.last() {
2369 err.span_suggestion_verbose(
2370 hir_field.span.shrink_to_hi(),
2371 msg,
2372 ", ..".to_string(),
2373 Applicability::MachineApplicable,
2374 );
2375 } else if hir_fields.is_empty() {
2376 err.span_suggestion_verbose(
2377 span.shrink_to_hi().with_hi(full_span.hi()),
2378 msg,
2379 " { .. }".to_string(),
2380 Applicability::MachineApplicable,
2381 );
2382 }
2383 }
2384
2385 if let Some(hir_field) = hir_fields.last() {
2386 self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
2387 } else {
2388 err.emit();
2389 }
2390 }
2391
2392 fn suggest_fru_from_range_and_emit(
2395 &self,
2396 last_expr_field: &hir::ExprField<'tcx>,
2397 variant: &ty::VariantDef,
2398 args: GenericArgsRef<'tcx>,
2399 mut err: Diag<'_>,
2400 ) {
2401 if is_range_literal(last_expr_field.expr)
2402 && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind
2403 && self.tcx.qpath_is_lang_item(qpath, LangItem::Range)
2404 && let variant_field =
2405 variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
2406 && let range_def_id = self.tcx.lang_items().range_struct()
2407 && variant_field
2408 .and_then(|field| field.ty(self.tcx, args).skip_norm_wip().ty_adt_def())
2409 .map(|adt| adt.did())
2410 != range_def_id
2411 {
2412 let expr = self
2416 .tcx
2417 .sess
2418 .source_map()
2419 .span_to_snippet(range_end.expr.span)
2420 .ok()
2421 .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control()));
2422
2423 let fru_span = self
2424 .tcx
2425 .sess
2426 .source_map()
2427 .span_extend_while_whitespace(range_start.expr.span)
2428 .shrink_to_hi()
2429 .to(range_end.expr.span);
2430
2431 err.subdiagnostic(TypeMismatchFruTypo {
2432 expr_span: range_start.expr.span,
2433 fru_span,
2434 expr,
2435 });
2436
2437 self.dcx().try_steal_replace_and_emit_err(
2439 last_expr_field.span,
2440 StashKey::MaybeFruTypo,
2441 err,
2442 );
2443 } else {
2444 err.emit();
2445 }
2446 }
2447
2448 fn report_private_fields(
2460 &self,
2461 adt_ty: Ty<'tcx>,
2462 span: Span,
2463 expr_span: Span,
2464 private_fields: Vec<&ty::FieldDef>,
2465 used_fields: &'tcx [hir::ExprField<'tcx>],
2466 ) {
2467 let mut err =
2468 self.dcx().struct_span_err(
2469 span,
2470 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot construct `{0}` with struct literal syntax due to private fields",
adt_ty))
})format!(
2471 "cannot construct `{adt_ty}` with struct literal syntax due to private fields",
2472 ),
2473 );
2474 let (used_private_fields, remaining_private_fields): (
2475 Vec<(Symbol, Span, bool)>,
2476 Vec<(Symbol, Span, bool)>,
2477 ) = private_fields
2478 .iter()
2479 .map(|field| {
2480 match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
2481 Some(used_field) => (field.name, used_field.span, true),
2482 None => (field.name, self.tcx.def_span(field.did), false),
2483 }
2484 })
2485 .partition(|field| field.2);
2486 err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
2487
2488 if let ty::Adt(def, _) = adt_ty.kind() {
2489 if (def.did().is_local() || !used_fields.is_empty())
2490 && !remaining_private_fields.is_empty()
2491 {
2492 let names = if remaining_private_fields.len() > 6 {
2493 String::new()
2494 } else {
2495 ::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!(
2496 "{} ",
2497 listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`"))
2498 .expect("expected at least one private field to report")
2499 )
2500 };
2501 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!(
2502 "{}private field{s} {names}that {were} not provided",
2503 if used_fields.is_empty() { "" } else { "...and other " },
2504 s = pluralize!(remaining_private_fields.len()),
2505 were = pluralize!("was", remaining_private_fields.len()),
2506 ));
2507 }
2508
2509 let def_id = def.did();
2510 let mut items = self
2511 .tcx
2512 .inherent_impls(def_id)
2513 .into_iter()
2514 .flat_map(|&i| self.tcx.associated_items(i).in_definition_order())
2515 .filter(|item| item.is_fn() && !item.is_method())
2517 .filter_map(|item| {
2518 let fn_sig = self
2520 .tcx
2521 .fn_sig(item.def_id)
2522 .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id))
2523 .skip_norm_wip();
2524 let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output());
2525 if !self.can_eq(self.param_env, ret_ty, adt_ty) {
2526 return None;
2527 }
2528 let input_len = fn_sig.inputs().skip_binder().len();
2529 let name = item.name();
2530 let order = !name.as_str().starts_with("new");
2531 Some((order, name, input_len))
2532 })
2533 .collect::<Vec<_>>();
2534 items.sort_by_key(|(order, _, _)| *order);
2535 let suggestion = |name, args| {
2536 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{1}({0})",
std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", "),
name))
})format!(
2537 "::{name}({})",
2538 std::iter::repeat_n("_", args).collect::<Vec<_>>().join(", ")
2539 )
2540 };
2541 match &items[..] {
2542 [] => {}
2543 [(_, name, args)] => {
2544 err.span_suggestion_verbose(
2545 span.shrink_to_hi().with_hi(expr_span.hi()),
2546 ::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"),
2547 suggestion(name, *args),
2548 Applicability::MaybeIncorrect,
2549 );
2550 }
2551 _ => {
2552 err.span_suggestions(
2553 span.shrink_to_hi().with_hi(expr_span.hi()),
2554 "you might have meant to use an associated function to build this type",
2555 items.iter().map(|(_, name, args)| suggestion(name, *args)),
2556 Applicability::MaybeIncorrect,
2557 );
2558 }
2559 }
2560 if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default)
2561 && self
2562 .infcx
2563 .type_implements_trait(default_trait, [adt_ty], self.param_env)
2564 .may_apply()
2565 {
2566 err.multipart_suggestion(
2567 "consider using the `Default` trait",
2568 ::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![
2569 (span.shrink_to_lo(), "<".to_string()),
2570 (
2571 span.shrink_to_hi().with_hi(expr_span.hi()),
2572 " as std::default::Default>::default()".to_string(),
2573 ),
2574 ],
2575 Applicability::MaybeIncorrect,
2576 );
2577 }
2578 }
2579
2580 err.emit();
2581 }
2582
2583 fn report_unknown_field(
2584 &self,
2585 ty: Ty<'tcx>,
2586 variant: &'tcx ty::VariantDef,
2587 expr: &hir::Expr<'_>,
2588 field: &hir::ExprField<'_>,
2589 skip_fields: &[hir::ExprField<'_>],
2590 kind_name: &str,
2591 ) -> ErrorGuaranteed {
2592 if let Err(guar) = variant.has_errors() {
2594 return guar;
2595 }
2596 let mut err = self.err_ctxt().type_error_struct_with_diag(
2597 field.ident.span,
2598 |actual| match ty.kind() {
2599 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!(
2600 self.dcx(),
2601 field.ident.span,
2602 E0559,
2603 "{} `{}::{}` has no field named `{}`",
2604 kind_name,
2605 actual,
2606 variant.name,
2607 field.ident
2608 ),
2609 _ => {
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!(
2610 self.dcx(),
2611 field.ident.span,
2612 E0560,
2613 "{} `{}` has no field named `{}`",
2614 kind_name,
2615 actual,
2616 field.ident
2617 ),
2618 },
2619 ty,
2620 );
2621
2622 let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
2623 match variant.ctor {
2624 Some((CtorKind::Fn, def_id)) => match ty.kind() {
2625 ty::Adt(adt, ..) if adt.is_enum() => {
2626 err.span_label(
2627 variant_ident_span,
2628 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` defined here", ty,
variant.name))
})format!(
2629 "`{adt}::{variant}` defined here",
2630 adt = ty,
2631 variant = variant.name,
2632 ),
2633 );
2634 err.span_label(field.ident.span, "field does not exist");
2635 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2636 let inputs = fn_sig.inputs().skip_binder();
2637 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!(
2638 "({})",
2639 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2640 );
2641 let (replace_span, sugg) = match expr.kind {
2642 hir::ExprKind::Struct(qpath, ..) => {
2643 (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields)
2644 }
2645 _ => {
2646 (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))
2647 }
2648 };
2649 err.span_suggestion_verbose(
2650 replace_span,
2651 ::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!(
2652 "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
2653 adt = ty,
2654 variant = variant.name,
2655 ),
2656 sugg,
2657 Applicability::HasPlaceholders,
2658 );
2659 }
2660 _ => {
2661 err.span_label(variant_ident_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", ty))
})format!("`{ty}` defined here"));
2662 err.span_label(field.ident.span, "field does not exist");
2663 let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
2664 let inputs = fn_sig.inputs().skip_binder();
2665 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!(
2666 "({})",
2667 inputs.iter().map(|i| format!("/* {i} */")).collect::<Vec<_>>().join(", ")
2668 );
2669 err.span_suggestion_verbose(
2670 expr.span,
2671 ::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",),
2672 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", ty, fields))
})format!("{ty}{fields}"),
2673 Applicability::HasPlaceholders,
2674 );
2675 }
2676 },
2677 _ => {
2678 let available_field_names = self.available_field_names(variant, expr, skip_fields);
2680 if let Some(field_name) =
2681 find_best_match_for_name(&available_field_names, field.ident.name, None)
2682 && !(field.ident.name.as_str().parse::<usize>().is_ok()
2683 && field_name.as_str().parse::<usize>().is_ok())
2684 {
2685 err.span_label(field.ident.span, "unknown field");
2686 err.span_suggestion_verbose(
2687 field.ident.span,
2688 "a field with a similar name exists",
2689 field_name,
2690 Applicability::MaybeIncorrect,
2691 );
2692 } else {
2693 match ty.kind() {
2694 ty::Adt(adt, ..) => {
2695 if adt.is_enum() {
2696 err.span_label(
2697 field.ident.span,
2698 ::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),
2699 );
2700 } else {
2701 err.span_label(
2702 field.ident.span,
2703 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` does not have this field",
ty))
})format!("`{ty}` does not have this field"),
2704 );
2705 }
2706 if available_field_names.is_empty() {
2707 err.note("all struct fields are already assigned");
2708 } else {
2709 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("available fields are: {0}",
self.name_series_display(available_field_names)))
})format!(
2710 "available fields are: {}",
2711 self.name_series_display(available_field_names)
2712 ));
2713 }
2714 }
2715 _ => ::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"),
2716 }
2717 };
2718 }
2719 }
2720 err.emit_err()
2721 }
2722
2723 fn available_field_names(
2724 &self,
2725 variant: &'tcx ty::VariantDef,
2726 expr: &hir::Expr<'_>,
2727 skip_fields: &[hir::ExprField<'_>],
2728 ) -> Vec<Symbol> {
2729 variant
2730 .fields
2731 .iter()
2732 .filter(|field| {
2733 skip_fields.iter().all(|&skip| skip.ident.name != field.name)
2734 && self.is_field_suggestable(field, expr.span)
2735 })
2736 .map(|field| field.name)
2737 .collect()
2738 }
2739
2740 fn name_series_display(&self, names: Vec<Symbol>) -> String {
2741 let limit = if names.len() == 6 { 6 } else { 5 };
2743 let mut display =
2744 names.iter().take(limit).map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")).collect::<Vec<_>>().join(", ");
2745 if names.len() > limit {
2746 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);
2747 }
2748 display
2749 }
2750
2751 fn find_adt_field(
2755 &self,
2756 base_def: ty::AdtDef<'tcx>,
2757 ident: Ident,
2758 ) -> Option<(FieldIdx, &'tcx ty::FieldDef)> {
2759 if base_def.is_enum() {
2761 return None;
2762 }
2763
2764 for (field_idx, field) in base_def.non_enum_variant().fields.iter_enumerated() {
2765 if field.ident(self.tcx).normalize_to_macros_2_0() == ident {
2766 return Some((field_idx, field));
2768 }
2769 }
2770
2771 None
2772 }
2773
2774 fn check_expr_field(
2784 &self,
2785 expr: &'tcx hir::Expr<'tcx>,
2786 base: &'tcx hir::Expr<'tcx>,
2787 field: Ident,
2788 expected: Expectation<'tcx>,
2790 ) -> Ty<'tcx> {
2791 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:2791",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2791u32),
::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);
2792 let base_ty = self.check_expr(base);
2793 let base_ty = self.structurally_resolve_type(base.span, base_ty);
2794
2795 let mut private_candidate = None;
2797
2798 let mut autoderef = self.autoderef(expr.span, base_ty);
2800 while let Some((deref_base_ty, _)) = autoderef.next() {
2801 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:2801",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2801u32),
::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);
2802 match deref_base_ty.kind() {
2803 ty::Adt(base_def, args) if !base_def.is_enum() => {
2804 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:2804",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(2804u32),
::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);
2805 if let Err(guar) = base_def.non_enum_variant().has_errors() {
2807 return Ty::new_error(self.tcx(), guar);
2808 }
2809
2810 let (ident, def_scope) =
2811 self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.mod_id);
2812
2813 if let Some((idx, field)) = self.find_adt_field(*base_def, ident) {
2814 self.write_field_index(expr.hir_id, idx);
2815
2816 let adjustments = self.adjust_steps(&autoderef);
2817 if field.vis.is_accessible_from(def_scope, self.tcx) {
2818 self.apply_adjustments(base, adjustments);
2819 self.register_predicates(autoderef.into_obligations());
2820
2821 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
2822 return self.field_ty(expr.span, field, args);
2823 }
2824
2825 private_candidate = Some((adjustments, base_def.did()));
2827 }
2828 }
2829 ty::Tuple(tys) => {
2830 if let Ok(index) = field.as_str().parse::<usize>() {
2831 if field.name == sym::integer(index) {
2832 if let Some(&field_ty) = tys.get(index) {
2833 let adjustments = self.adjust_steps(&autoderef);
2834 self.apply_adjustments(base, adjustments);
2835 self.register_predicates(autoderef.into_obligations());
2836
2837 self.write_field_index(expr.hir_id, FieldIdx::from_usize(index));
2838 return field_ty;
2839 }
2840 }
2841 }
2842 }
2843 _ => {}
2844 }
2845 }
2846 let final_ty = self.structurally_resolve_type(autoderef.span(), autoderef.final_ty());
2852 if let ty::Error(_) = final_ty.kind() {
2853 return final_ty;
2854 }
2855
2856 if let Some((adjustments, did)) = private_candidate {
2857 self.apply_adjustments(base, adjustments);
2860 let guar = self.ban_private_field_access(
2861 expr,
2862 base_ty,
2863 field,
2864 did,
2865 expected.only_has_type(self),
2866 );
2867 return Ty::new_error(self.tcx(), guar);
2868 }
2869
2870 let guar = if self.method_exists_for_diagnostic(
2871 field,
2872 base_ty,
2873 expr.hir_id,
2874 expected.only_has_type(self),
2875 ) {
2876 self.ban_take_value_of_method(expr, base_ty, field)
2878 } else if !base_ty.is_primitive_ty() {
2879 self.ban_nonexisting_field(field, base, expr, base_ty)
2880 } else {
2881 let field_name = field.to_string();
2882 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!(
2883 self.dcx(),
2884 field.span,
2885 base_ty,
2886 E0610,
2887 "`{base_ty}` is a primitive type and therefore doesn't have fields",
2888 );
2889 let is_valid_suffix = |field: &str| {
2890 if field == "f32" || field == "f64" {
2891 return true;
2892 }
2893 let mut chars = field.chars().peekable();
2894 match chars.peek() {
2895 Some('e') | Some('E') => {
2896 chars.next();
2897 if let Some(c) = chars.peek()
2898 && !c.is_numeric()
2899 && *c != '-'
2900 && *c != '+'
2901 {
2902 return false;
2903 }
2904 while let Some(c) = chars.peek() {
2905 if !c.is_numeric() {
2906 break;
2907 }
2908 chars.next();
2909 }
2910 }
2911 _ => (),
2912 }
2913 let suffix = chars.collect::<String>();
2914 suffix.is_empty() || suffix == "f32" || suffix == "f64"
2915 };
2916 let maybe_partial_suffix = |field: &str| -> Option<&str> {
2917 let first_chars = ['f', 'l'];
2918 if field.len() >= 1
2919 && field.to_lowercase().starts_with(first_chars)
2920 && field[1..].chars().all(|c| c.is_ascii_digit())
2921 {
2922 if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
2923 } else {
2924 None
2925 }
2926 };
2927 if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
2928 && let ExprKind::Lit(Spanned {
2929 node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
2930 ..
2931 }) = base.kind
2932 && !base.span.from_expansion()
2933 {
2934 if is_valid_suffix(&field_name) {
2935 err.span_suggestion_verbose(
2936 field.span.shrink_to_lo(),
2937 "if intended to be a floating point literal, consider adding a `0` after the period",
2938 '0',
2939 Applicability::MaybeIncorrect,
2940 );
2941 } else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
2942 err.span_suggestion_verbose(
2943 field.span,
2944 ::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"),
2945 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("0{0}", correct_suffix))
})format!("0{correct_suffix}"),
2946 Applicability::MaybeIncorrect,
2947 );
2948 }
2949 }
2950 err.emit_err()
2951 };
2952
2953 Ty::new_error(self.tcx(), guar)
2954 }
2955
2956 fn suggest_await_on_field_access(
2957 &self,
2958 err: &mut Diag<'_>,
2959 field_ident: Ident,
2960 base: &'tcx hir::Expr<'tcx>,
2961 ty: Ty<'tcx>,
2962 ) {
2963 let Some(output_ty) = self.tcx.get_impl_future_output_ty(ty) else {
2964 err.span_label(field_ident.span, "unknown field");
2965 return;
2966 };
2967 let ty::Adt(def, _) = output_ty.kind() else {
2968 err.span_label(field_ident.span, "unknown field");
2969 return;
2970 };
2971 if def.is_enum() {
2973 err.span_label(field_ident.span, "unknown field");
2974 return;
2975 }
2976 if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) {
2977 err.span_label(field_ident.span, "unknown field");
2978 return;
2979 }
2980 err.span_label(
2981 field_ident.span,
2982 "field not available in `impl Future`, but it is available in its `Output`",
2983 );
2984 match self.tcx.coroutine_kind(self.body_def_id) {
2985 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
2986 err.span_suggestion_verbose(
2987 base.span.shrink_to_hi(),
2988 "consider `await`ing on the `Future` to access the field",
2989 ".await",
2990 Applicability::MaybeIncorrect,
2991 );
2992 }
2993 _ => {
2994 let mut span: MultiSpan = base.span.into();
2995 span.push_span_label(self.tcx.def_span(self.body_def_id), "this is not `async`");
2996 err.span_note(
2997 span,
2998 "this implements `Future` and its output type has the field, \
2999 but the future cannot be awaited in a synchronous function",
3000 );
3001 }
3002 }
3003 }
3004
3005 fn ban_nonexisting_field(
3006 &self,
3007 ident: Ident,
3008 base: &'tcx hir::Expr<'tcx>,
3009 expr: &'tcx hir::Expr<'tcx>,
3010 base_ty: Ty<'tcx>,
3011 ) -> ErrorGuaranteed {
3012 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:3012",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3012u32),
::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!(
3013 "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
3014 ident, base, expr, base_ty
3015 );
3016 let mut err = self.no_such_field_err(ident, base_ty, expr);
3017
3018 match *base_ty.peel_refs().kind() {
3019 ty::Array(_, len) => {
3020 self.maybe_suggest_array_indexing(&mut err, base, ident, len);
3021 }
3022 ty::RawPtr(..) => {
3023 self.suggest_first_deref_field(&mut err, base, ident);
3024 }
3025 ty::Param(param_ty) => {
3026 err.span_label(ident.span, "unknown field");
3027 self.point_at_param_definition(&mut err, param_ty);
3028 }
3029 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
3030 self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
3031 }
3032 _ => {
3033 err.span_label(ident.span, "unknown field");
3034 }
3035 }
3036
3037 self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
3038 if let ty::Adt(def, _) = output_ty.kind()
3039 && !def.is_enum()
3040 {
3041 def.non_enum_variant().fields.iter().any(|field| {
3042 field.ident(self.tcx) == ident
3043 && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
3044 })
3045 } else if let ty::Tuple(tys) = output_ty.kind()
3046 && let Ok(idx) = ident.as_str().parse::<usize>()
3047 {
3048 idx < tys.len()
3049 } else {
3050 false
3051 }
3052 });
3053
3054 if ident.name == kw::Await {
3055 err.note("to `.await` a `Future`, switch to Rust 2018 or later");
3058 HelpUseLatestEdition::new().add_to_diag(&mut err);
3059 }
3060
3061 err.emit_err()
3062 }
3063
3064 fn ban_private_field_access(
3065 &self,
3066 expr: &hir::Expr<'tcx>,
3067 expr_t: Ty<'tcx>,
3068 field: Ident,
3069 base_did: DefId,
3070 return_ty: Option<Ty<'tcx>>,
3071 ) -> ErrorGuaranteed {
3072 let mut err = self.private_field_err(field, base_did);
3073
3074 if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty)
3076 && !self.expr_in_place(expr.hir_id)
3077 {
3078 self.suggest_method_call(
3079 &mut err,
3080 ::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"),
3081 field,
3082 expr_t,
3083 expr,
3084 None,
3085 );
3086 }
3087 err.emit_err()
3088 }
3089
3090 fn ban_take_value_of_method(
3091 &self,
3092 expr: &hir::Expr<'tcx>,
3093 expr_t: Ty<'tcx>,
3094 field: Ident,
3095 ) -> ErrorGuaranteed {
3096 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!(
3097 self.dcx(),
3098 field.span,
3099 expr_t,
3100 E0615,
3101 "attempted to take value of method `{field}` on type `{expr_t}`",
3102 );
3103 err.span_label(field.span, "method, not a field");
3104 let expr_is_call =
3105 if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
3106 self.tcx.parent_hir_node(expr.hir_id)
3107 {
3108 expr.hir_id == callee.hir_id
3109 } else {
3110 false
3111 };
3112 let expr_snippet =
3113 self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
3114 let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
3115 let after_open = expr.span.lo() + rustc_span::BytePos(1);
3116 let before_close = expr.span.hi() - rustc_span::BytePos(1);
3117
3118 if expr_is_call && is_wrapped {
3119 err.multipart_suggestion(
3120 "remove wrapping parentheses to call the method",
3121 ::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![
3122 (expr.span.with_hi(after_open), String::new()),
3123 (expr.span.with_lo(before_close), String::new()),
3124 ],
3125 Applicability::MachineApplicable,
3126 );
3127 } else if !self.expr_in_place(expr.hir_id) {
3128 let span = if is_wrapped {
3130 expr.span.with_lo(after_open).with_hi(before_close)
3131 } else {
3132 expr.span
3133 };
3134 self.suggest_method_call(
3135 &mut err,
3136 "use parentheses to call the method",
3137 field,
3138 expr_t,
3139 expr,
3140 Some(span),
3141 );
3142 } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind()
3143 && let ty::Adt(adt_def, _) = ptr_ty.kind()
3144 && let ExprKind::Field(base_expr, _) = expr.kind
3145 && let [variant] = &adt_def.variants().raw
3146 && variant.fields.iter().any(|f| f.ident(self.tcx) == field)
3147 {
3148 err.multipart_suggestion(
3149 "to access the field, dereference first",
3150 ::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![
3151 (base_expr.span.shrink_to_lo(), "(*".to_string()),
3152 (base_expr.span.shrink_to_hi(), ")".to_string()),
3153 ],
3154 Applicability::MaybeIncorrect,
3155 );
3156 } else {
3157 err.help("methods are immutable and cannot be assigned to");
3158 }
3159
3160 self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err)
3162 }
3163
3164 fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) {
3165 let generics = self.tcx.generics_of(self.body_def_id);
3166 let generic_param = generics.type_param(param, self.tcx);
3167 if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
3168 return;
3169 }
3170 let param_def_id = generic_param.def_id;
3171 let param_hir_id = match param_def_id.as_local() {
3172 Some(x) => self.tcx.local_def_id_to_hir_id(x),
3173 None => return,
3174 };
3175 let param_span = self.tcx.hir_span(param_hir_id);
3176 let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
3177
3178 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"));
3179 }
3180
3181 fn maybe_suggest_array_indexing(
3182 &self,
3183 err: &mut Diag<'_>,
3184 base: &hir::Expr<'_>,
3185 field: Ident,
3186 len: ty::Const<'tcx>,
3187 ) {
3188 err.span_label(field.span, "unknown field");
3189 if let (Some(len), Ok(user_index)) = (
3190 self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
3191 field.as_str().parse::<u64>(),
3192 ) {
3193 let help = "instead of using tuple indexing, use array indexing";
3194 let applicability = if len < user_index {
3195 Applicability::MachineApplicable
3196 } else {
3197 Applicability::MaybeIncorrect
3198 };
3199 err.multipart_suggestion(
3200 help,
3201 ::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![
3202 (base.span.between(field.span), "[".to_string()),
3203 (field.span.shrink_to_hi(), "]".to_string()),
3204 ],
3205 applicability,
3206 );
3207 }
3208 }
3209
3210 fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
3211 err.span_label(field.span, "unknown field");
3212 if base.span.from_expansion() || field.span.from_expansion() {
3213 return;
3214 }
3215 let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
3216 && base.len() < 20
3217 {
3218 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", base))
})format!("`{base}`")
3219 } else {
3220 "the value".to_string()
3221 };
3222 err.multipart_suggestion(
3223 ::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"),
3224 ::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![
3225 (base.span.shrink_to_lo(), "(*".into()),
3226 (base.span.between(field.span), format!(").")),
3227 ],
3228 Applicability::MaybeIncorrect,
3229 );
3230 }
3231
3232 fn no_such_field_err(
3233 &self,
3234 field: Ident,
3235 base_ty: Ty<'tcx>,
3236 expr: &hir::Expr<'tcx>,
3237 ) -> Diag<'_> {
3238 let span = field.span;
3239 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:3239",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3239u32),
::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);
3240
3241 let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
3242 if base_ty.references_error() {
3243 err.downgrade_to_delayed_bug();
3244 }
3245
3246 if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
3247 err.span_label(within_macro_span, "due to this macro variable");
3248 }
3249
3250 if let Some(def_id) = base_ty.peel_refs().ty_adt_def().map(|d| d.did()) {
3252 for &impl_def_id in self.tcx.inherent_impls(def_id) {
3253 for item in self.tcx.associated_items(impl_def_id).in_definition_order() {
3254 if let ExprKind::Field(base_expr, _) = expr.kind
3255 && item.name() == field.name
3256 && #[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, .. })
3257 {
3258 err.span_label(field.span, "this is an associated function, not a method");
3259 err.note("found the following associated function; to be used as method, it must have a `self` parameter");
3260 let impl_ty =
3261 self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip();
3262 err.span_note(
3263 self.tcx.def_span(item.def_id),
3264 ::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}`"),
3265 );
3266
3267 let ty_str = match base_ty.peel_refs().kind() {
3268 ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args),
3269 _ => base_ty.peel_refs().to_string(),
3270 };
3271 err.multipart_suggestion(
3272 "use associated function syntax instead",
3273 ::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![
3274 (base_expr.span, ty_str),
3275 (base_expr.span.between(field.span), "::".to_string()),
3276 ],
3277 Applicability::MaybeIncorrect,
3278 );
3279 return err;
3280 }
3281 }
3282 }
3283 }
3284
3285 let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
3287 && (self.tcx.is_diagnostic_item(sym::Result, def.did())
3288 || self.tcx.is_diagnostic_item(sym::Option, def.did()))
3289 && let Some(arg) = args.get(0)
3290 && let Some(ty) = arg.as_type()
3291 {
3292 (ty, "unwrap().")
3293 } else {
3294 (base_ty, "")
3295 };
3296 for found_fields in self.get_field_candidates_considering_privacy_for_diag(span, ty) {
3297 let field_names = found_fields.iter().map(|field| field.0.name).collect::<Vec<_>>();
3298 let mut candidate_fields: Vec<_> = found_fields
3299 .into_iter()
3300 .filter_map(|candidate_field| {
3301 self.check_for_nested_field_satisfying_condition_for_diag(
3302 span,
3303 &|candidate_field, _| candidate_field == field,
3304 candidate_field,
3305 ::alloc::vec::Vec::new()vec![],
3306 )
3307 })
3308 .map(|mut field_path| {
3309 field_path.pop();
3310 field_path.iter().map(|id| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.", id))
})format!("{}.", id)).collect::<String>()
3311 })
3312 .collect::<Vec<_>>();
3313 candidate_fields.sort();
3314
3315 let len = candidate_fields.len();
3316 if len > 0 && expr.span.eq_ctxt(field.span) {
3319 err.span_suggestions(
3320 field.span.shrink_to_lo(),
3321 ::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!(
3322 "{} of the expressions' fields {} a field of the same name",
3323 if len > 1 { "some" } else { "one" },
3324 if len > 1 { "have" } else { "has" },
3325 ),
3326 candidate_fields.iter().map(|path| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", unwrap, path))
})format!("{unwrap}{path}")),
3327 Applicability::MaybeIncorrect,
3328 );
3329 } else if let Some(field_name) =
3330 find_best_match_for_name(&field_names, field.name, None)
3331 && !(field.name.as_str().parse::<usize>().is_ok()
3332 && field_name.as_str().parse::<usize>().is_ok())
3333 {
3334 err.span_suggestion_verbose(
3335 field.span,
3336 "a field with a similar name exists",
3337 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}", field_name, unwrap))
})format!("{unwrap}{}", field_name),
3338 Applicability::MaybeIncorrect,
3339 );
3340 } else if !field_names.is_empty() {
3341 let is = if field_names.len() == 1 { " is" } else { "s are" };
3342 err.note(
3343 ::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),),
3344 );
3345 }
3346 }
3347 err
3348 }
3349
3350 fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> {
3351 let struct_path = self.tcx().def_path_str(base_did);
3352 let kind_name = self.tcx().def_descr(base_did);
3353 {
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!(
3354 self.dcx(),
3355 field.span,
3356 E0616,
3357 "field `{field}` of {kind_name} `{struct_path}` is private",
3358 )
3359 .with_span_label(field.span, "private field")
3360 }
3361
3362 pub(crate) fn get_field_candidates_considering_privacy_for_diag(
3363 &self,
3364 span: Span,
3365 base_ty: Ty<'tcx>,
3366 ) -> Vec<Vec<(Ident, Ty<'tcx>)>> {
3367 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs:3367",
"rustc_hir_typeck::expr", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3367u32),
::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);
3368
3369 let mut autoderef = self.autoderef(span, base_ty).silence_errors();
3370 let deref_chain: Vec<_> = autoderef.by_ref().collect();
3371
3372 if autoderef.reached_recursion_limit() {
3376 return ::alloc::vec::Vec::new()vec![];
3377 }
3378
3379 deref_chain
3380 .into_iter()
3381 .filter_map(move |(base_t, _)| {
3382 match base_t.kind() {
3383 ty::Adt(base_def, args) if !base_def.is_enum() => {
3384 let tcx = self.tcx;
3385 let fields = &base_def.non_enum_variant().fields;
3386 if fields
3390 .iter()
3391 .all(|field| !field.vis.is_accessible_from(self.mod_id, tcx))
3392 {
3393 return None;
3394 }
3395 return Some(
3396 fields
3397 .iter()
3398 .filter(move |field| {
3399 field.vis.is_accessible_from(self.mod_id, tcx)
3400 && self.is_field_suggestable(field, span)
3401 })
3402 .take(100)
3404 .map(|field_def| {
3405 (
3406 field_def.ident(self.tcx).normalize_to_macros_2_0(),
3407 field_def.ty(self.tcx, args).skip_norm_wip(),
3408 )
3409 })
3410 .collect::<Vec<_>>(),
3411 );
3412 }
3413 ty::Tuple(types) => {
3414 return Some(
3415 types
3416 .iter()
3417 .enumerate()
3418 .take(100)
3420 .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty))
3421 .collect::<Vec<_>>(),
3422 );
3423 }
3424 _ => None,
3425 }
3426 })
3427 .collect()
3428 }
3429
3430 {}
#[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/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_hir_typeck/src/expr.rs"),
::tracing_core::__macro_support::Option::Some(3432u32),
::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")]
3433 pub(crate) fn check_for_nested_field_satisfying_condition_for_diag(
3434 &self,
3435 span: Span,
3436 matches: &impl Fn(Ident, Ty<'tcx>) -> bool,
3437 (candidate_name, candidate_ty): (Ident, Ty<'tcx>),
3438 mut field_path: Vec<Ident>,
3439 ) -> Option<Vec<Ident>> {
3440 if field_path.len() > 3 {
3441 return None;
3444 }
3445 field_path.push(candidate_name);
3446 if matches(candidate_name, candidate_ty) {
3447 return Some(field_path);
3448 }
3449 for nested_fields in
3450 self.get_field_candidates_considering_privacy_for_diag(span, candidate_ty)
3451 {
3452 for field in nested_fields {
3454 if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag(
3455 span,
3456 matches,
3457 field,
3458 field_path.clone(),
3459 ) {
3460 return Some(field_path);
3461 }
3462 }
3463 }
3464 None
3465 }
3466
3467 fn check_expr_index(
3468 &self,
3469 base: &'tcx hir::Expr<'tcx>,
3470 idx: &'tcx hir::Expr<'tcx>,
3471 expr: &'tcx hir::Expr<'tcx>,
3472 brackets_span: Span,
3473 ) -> Ty<'tcx> {
3474 let base_t = self.check_expr(base);
3475 let idx_t = self.check_expr(idx);
3476
3477 if base_t.references_error() {
3478 base_t
3479 } else if idx_t.references_error() {
3480 idx_t
3481 } else {
3482 let base_t = self.structurally_resolve_type(base.span, base_t);
3483 match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
3484 Some((index_ty, element_ty)) => {
3485 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3487 self.select_obligations_where_possible(|errors| {
3488 self.point_at_index(errors, idx.span);
3489 });
3490 element_ty
3491 }
3492 None => {
3493 for (base_t, _) in self.autoderef(base.span, base_t).silence_errors() {
3496 if let Some((_, index_ty, element_ty)) =
3497 self.find_and_report_unsatisfied_index_impl(base, base_t)
3498 {
3499 self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
3500 return element_ty;
3501 }
3502 }
3503
3504 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!(
3505 self.dcx(),
3506 brackets_span,
3507 base_t,
3508 E0608,
3509 "cannot index into a value of type `{base_t}`",
3510 );
3511 if let ty::Tuple(types) = base_t.kind() {
3513 err.help(
3514 "tuples are indexed with a dot and a literal index: `tuple.0`, `tuple.1`, etc.",
3515 );
3516 if let ExprKind::Lit(lit) = idx.kind
3518 && let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
3519 && i.get() < types.len().try_into().expect("tuple length fits in u128")
3520 {
3521 err.span_suggestion(
3522 brackets_span,
3523 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("to access tuple element `{0}`, use",
i))
})format!("to access tuple element `{i}`, use"),
3524 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!(".{0}", i)) })format!(".{i}"),
3525 Applicability::MachineApplicable,
3526 );
3527 }
3528 }
3529
3530 if base_t.is_raw_ptr() && idx_t.is_integral() {
3531 err.multipart_suggestion(
3532 "consider using `wrapping_add` or `add` for indexing into raw pointer",
3533 ::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![
3534 (base.span.between(idx.span), ".wrapping_add(".to_owned()),
3535 (
3536 idx.span.shrink_to_hi().until(expr.span.shrink_to_hi()),
3537 ")".to_owned(),
3538 ),
3539 ],
3540 Applicability::MaybeIncorrect,
3541 );
3542 }
3543
3544 let guar = err.emit_err();
3545 Ty::new_error(self.tcx, guar)
3546 }
3547 }
3548 }
3549 }
3550
3551 fn find_and_report_unsatisfied_index_impl(
3559 &self,
3560 base_expr: &hir::Expr<'_>,
3561 base_ty: Ty<'tcx>,
3562 ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)> {
3563 let index_trait_def_id = self.tcx.lang_items().index_trait()?;
3564 let index_trait_output_def_id = self.tcx.get_diagnostic_item(sym::IndexOutput)?;
3565
3566 let mut relevant_impls = ::alloc::vec::Vec::new()vec![];
3567 self.tcx.for_each_relevant_impl(index_trait_def_id, base_ty, |impl_def_id| {
3568 relevant_impls.push(impl_def_id);
3569 });
3570 let [impl_def_id] = relevant_impls[..] else {
3571 return None;
3573 };
3574
3575 self.commit_if_ok(|snapshot| {
3576 let outer_universe = self.universe();
3577
3578 let ocx = ObligationCtxt::new_with_diagnostics(self);
3579 let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id);
3580 let impl_trait_ref =
3581 self.tcx.impl_trait_ref(impl_def_id).instantiate(self.tcx, impl_args);
3582 let cause = self.misc(base_expr.span);
3583
3584 let impl_trait_ref = ocx.normalize(&cause, self.param_env, impl_trait_ref);
3587 ocx.eq(&cause, self.param_env, base_ty, impl_trait_ref.self_ty())?;
3588
3589 let unnormalized_clauses =
3593 self.tcx.clauses_of(impl_def_id).instantiate(self.tcx, impl_args);
3594 ocx.register_obligations(traits::predicates_for_generics(
3595 |idx, span| {
3596 cause.clone().derived_cause(
3597 ty::Binder::dummy(ty::TraitClause {
3598 trait_ref: impl_trait_ref,
3599 polarity: ty::ClausePolarity::Positive,
3600 }),
3601 |derived| {
3602 ObligationCauseCode::ImplDerived(Box::new(traits::ImplDerivedCause {
3603 derived,
3604 impl_or_alias_def_id: impl_def_id,
3605 impl_def_clause_index: Some(idx),
3606 span,
3607 }))
3608 },
3609 )
3610 },
3611 |clause| ocx.normalize(&cause, self.param_env, clause),
3612 self.param_env,
3613 unnormalized_clauses,
3614 ));
3615
3616 let element_ty = ocx.normalize(
3619 &cause,
3620 self.param_env,
3621 Unnormalized::new(Ty::new_projection_from_args(
3622 self.tcx,
3623 ty::IsRigid::No,
3624 index_trait_output_def_id,
3625 impl_trait_ref.args,
3626 )),
3627 );
3628
3629 let true_errors = ocx.try_evaluate_obligations();
3630
3631 self.leak_check(outer_universe, Some(snapshot))?;
3635
3636 let ambiguity_errors = ocx.evaluate_obligations_error_on_ambiguity();
3638 if true_errors.no_errors() && ambiguity_errors.has_errors() {
3639 return Err(NoSolution);
3640 }
3641
3642 Ok::<_, NoSolution>((
3645 self.err_ctxt().report_fulfillment_errors(true_errors.into_thin_vec()),
3646 impl_trait_ref.args.type_at(1),
3647 element_ty,
3648 ))
3649 })
3650 .ok()
3651 }
3652
3653 fn point_at_index(&self, errors: &mut ThinVec<traits::FulfillmentError<'tcx>>, span: Span) {
3654 let mut seen_preds = FxHashSet::default();
3655 errors.sort_by_key(|error| error.root_obligation.recursion_depth);
3659 for error in errors {
3660 match (
3661 error.root_obligation.predicate.kind().skip_binder(),
3662 error.obligation.predicate.kind().skip_binder(),
3663 ) {
3664 (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _)
3665 if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) =>
3666 {
3667 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3668 }
3669 (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)))
3670 if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) =>
3671 {
3672 seen_preds.insert(error.obligation.predicate.kind().skip_binder());
3673 }
3674 (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {}
3675 _ => continue,
3676 }
3677 error.obligation.cause.span = span;
3678 }
3679 }
3680
3681 fn check_expr_yield(
3682 &self,
3683 value: &'tcx hir::Expr<'tcx>,
3684 expr: &'tcx hir::Expr<'tcx>,
3685 ) -> Ty<'tcx> {
3686 match self.coroutine_types {
3687 Some(CoroutineTypes { resume_ty, yield_ty }) => {
3688 self.check_expr_coercible_to_type(value, yield_ty, None);
3689
3690 resume_ty
3691 }
3692 _ => {
3693 self.dcx().emit_err(YieldExprOutsideOfCoroutine { span: expr.span });
3694 self.check_expr(value);
3696 self.tcx.types.unit
3697 }
3698 }
3699 }
3700
3701 fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
3702 let needs = if is_input { Needs::None } else { Needs::MutPlace };
3703 let ty = self.check_expr_with_needs(expr, needs);
3704 self.require_type_is_sized(ty, expr.span, ObligationCauseCode::InlineAsmSized);
3705
3706 if !is_input && !expr.is_syntactic_place_expr() {
3707 self.dcx()
3708 .struct_span_err(expr.span, "invalid asm output")
3709 .with_span_label(expr.span, "cannot assign to this expression")
3710 .emit();
3711 }
3712
3713 if is_input {
3721 let ty = self.structurally_resolve_type(expr.span, ty);
3722 match *ty.kind() {
3723 ty::FnDef(..) => {
3724 let fnptr_ty = Ty::new_fn_ptr(self.tcx, ty.fn_sig(self.tcx));
3725 self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
3726 }
3727 ty::Ref(_, base_ty, mutbl) => {
3728 let ptr_ty = Ty::new_ptr(self.tcx, base_ty, mutbl);
3729 self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
3730 }
3731 _ => {}
3732 }
3733 }
3734 }
3735
3736 fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>, span: Span) -> Ty<'tcx> {
3737 if let rustc_ast::AsmMacro::NakedAsm = asm.asm_macro {
3738 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(..)) {
3739 self.tcx.dcx().emit_err(NakedAsmOutsideNakedFn { span });
3740 }
3741 }
3742
3743 let mut diverge = asm.asm_macro.diverges(asm.options);
3744
3745 for (op, _op_sp) in asm.operands {
3746 match *op {
3747 hir::InlineAsmOperand::In { expr, .. } => {
3748 self.check_expr_asm_operand(expr, true);
3749 }
3750 hir::InlineAsmOperand::Out { expr: Some(expr), .. }
3751 | hir::InlineAsmOperand::InOut { expr, .. } => {
3752 self.check_expr_asm_operand(expr, false);
3753 }
3754 hir::InlineAsmOperand::Out { expr: None, .. } => {}
3755 hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
3756 self.check_expr_asm_operand(in_expr, true);
3757 if let Some(out_expr) = out_expr {
3758 self.check_expr_asm_operand(out_expr, false);
3759 }
3760 }
3761 hir::InlineAsmOperand::Const { ref anon_const } => {
3762 let body = self.tcx.hir_body(anon_const.body);
3766
3767 let fcx = FnCtxt::new(self, self.param_env, anon_const.def_id);
3768 let ty = fcx.check_expr(body.value);
3769 let target_ty = match self.structurally_resolve_type(body.value.span, ty).kind()
3770 {
3771 ty::FnDef(..) => {
3772 let fn_sig = ty.fn_sig(self.tcx());
3773 Ty::new_fn_ptr(self.tcx(), fn_sig)
3774 }
3775 ty::Closure(_, args) => {
3776 let closure_sig = args.as_closure().sig();
3777 let fn_sig =
3778 self.tcx().signature_unclosure(closure_sig, hir::Safety::Safe);
3779 Ty::new_fn_ptr(self.tcx(), fn_sig)
3780 }
3781 _ => ty,
3782 };
3783
3784 if let Err(diag) =
3785 self.demand_coerce_diag(&body.value, ty, target_ty, None, AllowTwoPhase::No)
3786 {
3787 diag.emit();
3788 }
3789
3790 fcx.require_type_is_sized(
3791 target_ty,
3792 body.value.span,
3793 ObligationCauseCode::SizedConstOrStatic,
3794 );
3795 fcx.write_ty(anon_const.hir_id, target_ty);
3796 }
3797 hir::InlineAsmOperand::SymFn { expr } => {
3798 self.check_expr(expr);
3799 }
3800 hir::InlineAsmOperand::SymStatic { .. } => {}
3801 hir::InlineAsmOperand::Label { block } => {
3802 let previous_diverges = self.diverges.get();
3803
3804 let ty = self.check_expr_block(block, ExpectHasType(self.tcx.types.unit));
3806 if !ty.is_never() {
3807 self.demand_suptype(block.span, self.tcx.types.unit, ty);
3808 diverge = false;
3809 }
3810
3811 self.diverges.set(previous_diverges);
3813 }
3814 }
3815 }
3816
3817 if diverge { self.tcx.types.never } else { self.tcx.types.unit }
3818 }
3819
3820 fn check_expr_offset_of(
3821 &self,
3822 container: &'tcx hir::Ty<'tcx>,
3823 fields: &[Ident],
3824 expr: &'tcx hir::Expr<'tcx>,
3825 ) -> Ty<'tcx> {
3826 let mut current_container = self.lower_ty(container).normalized;
3827 let mut field_indices = Vec::with_capacity(fields.len());
3828 let mut fields = fields.into_iter();
3829
3830 while let Some(&field) = fields.next() {
3831 let container = self.structurally_resolve_type(expr.span, current_container);
3832
3833 match container.kind() {
3834 ty::Adt(container_def, args) if container_def.is_enum() => {
3835 let ident = self.tcx.adjust_ident(field, container_def.did());
3836
3837 if !self.tcx.features().offset_of_enum() {
3838 rustc_session::diagnostics::feature_err(
3839 &self.tcx.sess,
3840 sym::offset_of_enum,
3841 ident.span,
3842 "using enums in offset_of is experimental",
3843 )
3844 .emit();
3845 }
3846
3847 let Some((index, variant)) = container_def
3848 .variants()
3849 .iter_enumerated()
3850 .find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
3851 else {
3852 self.dcx()
3853 .create_err(NoVariantNamed { span: ident.span, ident, ty: container })
3854 .with_span_label(field.span, "variant not found")
3855 .emit_err_unless_delay(container.references_error());
3856 break;
3857 };
3858 let Some(&subfield) = fields.next() else {
3859 {
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!(
3860 self.dcx(),
3861 ident.span,
3862 container,
3863 E0795,
3864 "`{ident}` is an enum variant; expected field at end of `offset_of`",
3865 )
3866 .with_span_label(field.span, "enum variant")
3867 .emit();
3868 break;
3869 };
3870 let (subident, sub_def_scope) =
3871 self.tcx.adjust_ident_and_get_scope(subfield, variant.def_id, self.mod_id);
3872
3873 let Some((subindex, field)) = variant
3874 .fields
3875 .iter_enumerated()
3876 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == subident)
3877 else {
3878 self.dcx()
3879 .create_err(NoFieldOnVariant {
3880 span: ident.span,
3881 container,
3882 ident,
3883 field: subfield,
3884 enum_span: field.span,
3885 field_span: subident.span,
3886 })
3887 .emit_err_unless_delay(container.references_error());
3888 break;
3889 };
3890
3891 let field_ty = self.field_ty(expr.span, field, args);
3892
3893 self.require_type_is_sized(
3896 field_ty,
3897 expr.span,
3898 ObligationCauseCode::FieldSized {
3899 adt_kind: AdtKind::Enum,
3900 span: self.tcx.def_span(field.did),
3901 last: false,
3902 },
3903 );
3904
3905 if field.vis.is_accessible_from(sub_def_scope, self.tcx) {
3906 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3907 } else {
3908 self.private_field_err(ident, container_def.did()).emit();
3909 }
3910
3911 field_indices.push((current_container, index, subindex));
3914 current_container = field_ty;
3915
3916 continue;
3917 }
3918 ty::Adt(container_def, args) => {
3919 let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(
3920 field,
3921 container_def.did(),
3922 self.mod_id,
3923 );
3924
3925 let fields = &container_def.non_enum_variant().fields;
3926 if let Some((index, field)) = fields
3927 .iter_enumerated()
3928 .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
3929 {
3930 let field_ty = self.field_ty(expr.span, field, args);
3931
3932 if self.tcx.features().offset_of_slice() {
3933 self.require_type_has_static_alignment(field_ty, expr.span);
3934 } else {
3935 self.require_type_is_sized(
3936 field_ty,
3937 expr.span,
3938 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(expr.hir_id)),
3939 );
3940 }
3941
3942 if field.vis.is_accessible_from(def_scope, self.tcx) {
3943 self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
3944 } else {
3945 self.private_field_err(ident, container_def.did()).emit();
3946 }
3947
3948 field_indices.push((current_container, FIRST_VARIANT, index));
3951 current_container = field_ty;
3952
3953 continue;
3954 }
3955 }
3956 ty::Tuple(tys) => {
3957 if let Ok(index) = field.as_str().parse::<usize>()
3958 && field.name == sym::integer(index)
3959 {
3960 if let Some(&field_ty) = tys.get(index) {
3961 if self.tcx.features().offset_of_slice() {
3962 self.require_type_has_static_alignment(field_ty, expr.span);
3963 } else {
3964 self.require_type_is_sized(
3965 field_ty,
3966 expr.span,
3967 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(
3968 expr.hir_id,
3969 )),
3970 );
3971 }
3972
3973 field_indices.push((current_container, FIRST_VARIANT, index.into()));
3974 current_container = field_ty;
3975
3976 continue;
3977 }
3978 }
3979 }
3980 _ => (),
3981 };
3982
3983 self.no_such_field_err(field, container, expr).emit();
3984
3985 break;
3986 }
3987
3988 self.typeck_results.borrow_mut().offset_of_data_mut().insert(expr.hir_id, field_indices);
3989
3990 self.tcx.types.usize
3991 }
3992}