1use std::cell::LazyCell;
2use std::ops::ControlFlow;
3
4use rustc_abi::{ExternAbi, FieldIdx, MAX_SIMD_LANES, ScalableElt};
5use rustc_data_structures::unord::{UnordMap, UnordSet};
6use rustc_errors::codes::*;
7use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan};
8use rustc_hir as hir;
9use rustc_hir::attrs::ReprAttr::ReprPacked;
10use rustc_hir::attrs::lang_items::LangItem;
11use rustc_hir::def::{CtorKind, DefKind};
12use rustc_hir::{Node, find_attr, intravisit};
13use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
14use rustc_infer::traits::{Obligation, ObligationCauseCode, TraitErrors, WellFormedLoc};
15use rustc_lint_defs::builtin::{
16 ALIGNED_FIELDS_IN_PACKED, DEAD_CODE, UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS,
17};
18use rustc_macros::Diagnostic;
19use rustc_middle::hir::nested_filter;
20use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
21use rustc_middle::middle::stability::EvalResult;
22use rustc_middle::ty::error::TypeErrorToStringExt;
23use rustc_middle::ty::layout::LayoutError;
24use rustc_middle::ty::util::Discr;
25use rustc_middle::ty::{
26 AdtDef, BottomUpFolder, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,
27 TypeVisitable, TypeVisitableExt, Unnormalized, fold_regions,
28};
29use rustc_span::sym;
30use rustc_target::spec::{AbiMap, AbiMapping};
31use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
32use rustc_trait_selection::traits;
33use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
34use tracing::{debug, instrument};
35use ty::TypingMode;
36
37use super::compare_impl_item::check_type_bounds;
38use super::*;
39use crate::check::wfcheck::{
40 check_associated_item, check_trait_item, check_type_defn, check_variances_for_type_defn,
41 check_where_clauses, enter_wf_checking_ctxt,
42};
43use crate::collect::ItemCtxt;
44use crate::diagnostics;
45
46fn add_abi_diag_help<G>(abi: ExternAbi, diag: &mut Diag<'_, G>) {
47 if let ExternAbi::Cdecl { unwind } = abi {
48 let c_abi = ExternAbi::C { unwind };
49 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use `extern {0}` instead", c_abi))
})format!("use `extern {c_abi}` instead",));
50 } else if let ExternAbi::Stdcall { unwind } = abi {
51 let c_abi = ExternAbi::C { unwind };
52 let system_abi = ExternAbi::System { unwind };
53 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you need `extern {0}` on win32 and `extern {1}` everywhere else, use `extern {2}`",
abi, c_abi, system_abi))
})format!(
54 "if you need `extern {abi}` on win32 and `extern {c_abi}` everywhere else, \
55 use `extern {system_abi}`"
56 ));
57 }
58}
59
60pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {
61 struct UnsupportedCallingConventions {
62 abi: ExternAbi,
63 }
64
65 impl<'a> Diagnostic<'a, ()> for UnsupportedCallingConventions {
66 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
67 let Self { abi } = self;
68 let mut lint = Diag::new(
69 dcx,
70 level,
71 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not a supported ABI for the current target",
abi))
})format!("{abi} is not a supported ABI for the current target"),
72 );
73 add_abi_diag_help(abi, &mut lint);
74 lint
75 }
76 }
77 match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {
82 AbiMapping::Direct(..) => (),
83 AbiMapping::Invalid => {
85 tcx.dcx().span_delayed_bug(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} should be rejected in ast_lowering",
abi))
})format!("{abi} should be rejected in ast_lowering"));
86 }
87 AbiMapping::Deprecated(..) => {
88 tcx.emit_node_span_lint(
89 UNSUPPORTED_CALLING_CONVENTIONS,
90 hir_id,
91 span,
92 UnsupportedCallingConventions { abi },
93 );
94 }
95 }
96}
97
98fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
99 let def = tcx.adt_def(def_id);
100 let span = tcx.def_span(def_id);
101 def.destructor(tcx); if let Some(scalable) = def.repr().scalable {
104 check_scalable_vector(tcx, span, def_id, scalable);
105 } else if def.repr().simd() {
106 check_simd(tcx, span, def_id);
107 }
108
109 check_transparent(tcx, def);
110 check_packed(tcx, span, def_id);
111 check_type_defn(tcx, def_id, false)
112}
113
114fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
115 let def = tcx.adt_def(def_id);
116 let span = tcx.def_span(def_id);
117 def.destructor(tcx); check_transparent(tcx, def);
119 check_union_fields(tcx, span, def_id);
120 check_packed(tcx, span, def_id);
121 check_type_defn(tcx, def_id, true)
122}
123
124fn allowed_union_or_unsafe_field<'tcx>(
125 tcx: TyCtxt<'tcx>,
126 ty: Ty<'tcx>,
127 typing_env: ty::TypingEnv<'tcx>,
128 span: Span,
129) -> bool {
130 if ty.is_trivially_pure_clone_copy() {
135 return true;
136 }
137 let def_id = tcx
140 .lang_items()
141 .get(LangItem::BikeshedGuaranteedNoDrop)
142 .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));
143 let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)) else {
144 tcx.dcx().span_delayed_bug(span, "could not normalize field type");
145 return true;
146 };
147 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
148 infcx.predicate_must_hold_modulo_regions(&Obligation::new(
149 tcx,
150 ObligationCause::dummy_with_span(span),
151 param_env,
152 ty::TraitRef::new(tcx, def_id, [ty]),
153 ))
154}
155
156fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
158 let def = tcx.adt_def(item_def_id);
159 if !def.is_union() {
::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
160
161 let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
162 let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
163
164 for field in &def.non_enum_variant().fields {
165 if !allowed_union_or_unsafe_field(
166 tcx,
167 field.ty(tcx, args).skip_norm_wip(),
168 typing_env,
169 span,
170 ) {
171 let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
172 Some(Node::Field(field)) => (field.span, field.ty.span),
174 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("mir field has to correspond to hir field")));
}unreachable!("mir field has to correspond to hir field"),
175 };
176 tcx.dcx().emit_err(diagnostics::InvalidUnionField {
177 field_span,
178 sugg: diagnostics::InvalidUnionFieldSuggestion {
179 lo: ty_span.shrink_to_lo(),
180 hi: ty_span.shrink_to_hi(),
181 },
182 note: (),
183 });
184 return false;
185 }
186 }
187
188 true
189}
190
191fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
193 #[derive(const _: () =
{
impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
StaticOfUninhabitedType {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
match self {
StaticOfUninhabitedType => {
let mut diag =
rustc_errors::Diag::new(dcx, level,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("static of uninhabited type")));
diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("uninhabited statics cannot be initialized, and any access would be an immediate error")));
;
diag
}
}
}
}
};Diagnostic)]
194 #[diag("static of uninhabited type")]
195 #[note("uninhabited statics cannot be initialized, and any access would be an immediate error")]
196 struct StaticOfUninhabitedType;
197
198 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
204 let span = tcx.def_span(def_id);
205 let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
206 Ok(l) => l,
207 Err(LayoutError::SizeOverflow(_))
209 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
DefKind::Static { .. } if
tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod => true,
_ => false,
}matches!(tcx.def_kind(def_id), DefKind::Static{ .. }
210 if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
211 {
212 tcx.dcx().emit_err(diagnostics::TooLargeStatic { span });
213 return;
214 }
215 Err(e @ LayoutError::InvalidSimd { .. }) => {
217 let ty_span = tcx.ty_span(def_id);
218 tcx.dcx().span_err(ty_span, e.to_string());
219 return;
220 }
221 Err(e) => {
223 tcx.dcx().span_delayed_bug(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", e))
})format!("{e:?}"));
224 return;
225 }
226 };
227 if layout.is_uninhabited() {
228 tcx.emit_node_span_lint(
229 UNINHABITED_STATIC,
230 tcx.local_def_id_to_hir_id(def_id),
231 span,
232 StaticOfUninhabitedType,
233 );
234 }
235}
236
237fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
240 let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
241
242 if tcx.sess.opts.actually_rustdoc {
247 return;
248 }
249
250 if tcx.type_of(def_id).instantiate_identity().skip_norm_wip().references_error() {
251 return;
252 }
253 if check_opaque_for_cycles(tcx, def_id).is_err() {
254 return;
255 }
256
257 let _ = check_opaque_meets_bounds(tcx, def_id, origin);
258}
259
260fn check_opaque_for_cycles<'tcx>(
262 tcx: TyCtxt<'tcx>,
263 def_id: LocalDefId,
264) -> Result<(), ErrorGuaranteed> {
265 let args = GenericArgs::identity_for_item(tcx, def_id);
266
267 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
270 let reported = opaque_type_cycle_error(tcx, def_id);
271 return Err(reported);
272 }
273
274 Ok(())
275}
276
277{}
#[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_opaque_meets_bounds",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(292u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("origin")
}> =
::tracing::__macro_support::FieldName::new("origin");
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(&def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&origin)
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: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let (span, definition_def_id) =
if let Some((span, def_id)) =
best_definition_site_of_opaque(tcx, def_id, origin) {
(span, Some(def_id))
} else { (tcx.def_span(def_id), None) };
let defining_use_anchor =
match origin {
hir::OpaqueTyOrigin::FnReturn { parent, .. } |
hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
};
let param_env = tcx.param_env(defining_use_anchor);
let infcx =
tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
} else {
TypingMode::analysis_in_body(tcx, defining_use_anchor)
});
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
let args =
match origin {
hir::OpaqueTyOrigin::FnReturn { parent, .. } |
hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
hir::OpaqueTyOrigin::TyAlias { parent, .. } =>
GenericArgs::identity_for_item(tcx,
parent).extend_to(tcx, def_id.to_def_id(),
|param, _|
{
tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
}),
};
let opaque_ty =
Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(),
args);
let hidden_ty =
tcx.type_of(def_id.to_def_id()).instantiate(tcx,
args).skip_norm_wip();
let hidden_ty =
fold_regions(tcx, hidden_ty,
|re, _dbi|
match re.kind() {
ty::ReErased =>
infcx.next_region_var(RegionVariableOrigin::Misc(span)),
_ => re,
});
for (predicate, pred_span) in
tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx,
args).map(Unnormalized::skip_norm_wip) {
let predicate =
predicate.fold_with(&mut BottomUpFolder {
tcx,
ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
lt_op: |lt| lt,
ct_op: |ct| ct,
});
ocx.register_obligation(Obligation::new(tcx,
ObligationCause::new(span, def_id,
ObligationCauseCode::OpaqueTypeBound(pred_span,
definition_def_id)), param_env, predicate));
}
let misc_cause = ObligationCause::misc(span, def_id);
match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
Ok(()) => {}
Err(ty_err) => {
let ty_err = ty_err.to_string(tcx);
let guar =
tcx.dcx().span_delayed_bug(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not unify `{0}` with revealed type:\n{1}",
hidden_ty, ty_err))
}));
return Err(guar);
}
}
let predicate =
ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(),
param_env, predicate));
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if let TraitErrors::HasErrors(errors) = errors {
let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(guar);
}
let wf_tys =
ocx.assumed_wf_types_and_report_errors(param_env,
defining_use_anchor)?;
ocx.resolve_regions_and_report_errors(defining_use_anchor,
param_env, wf_tys)?;
if infcx.next_trait_solver() {
Ok(())
} else if let hir::OpaqueTyOrigin::FnReturn { .. } |
hir::OpaqueTyOrigin::AsyncFn { .. } = origin {
let _ = infcx.take_opaque_types();
Ok(())
} else {
for (mut key, mut ty) in infcx.take_opaque_types() {
ty.ty = infcx.deeply_resolve_ignoring_regions(ty.ty);
key = infcx.deeply_resolve_ignoring_regions(key);
sanity_check_found_hidden_type(tcx, key, ty)?;
}
Ok(())
}
}
}
}#[instrument(level = "debug", skip(tcx))]
293fn check_opaque_meets_bounds<'tcx>(
294 tcx: TyCtxt<'tcx>,
295 def_id: LocalDefId,
296 origin: hir::OpaqueTyOrigin<LocalDefId>,
297) -> Result<(), ErrorGuaranteed> {
298 let (span, definition_def_id) =
299 if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
300 (span, Some(def_id))
301 } else {
302 (tcx.def_span(def_id), None)
303 };
304
305 let defining_use_anchor = match origin {
306 hir::OpaqueTyOrigin::FnReturn { parent, .. }
307 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
308 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
309 };
310 let param_env = tcx.param_env(defining_use_anchor);
311
312 let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
314 TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
315 } else {
316 TypingMode::analysis_in_body(tcx, defining_use_anchor)
317 });
318 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
319
320 let args = match origin {
321 hir::OpaqueTyOrigin::FnReturn { parent, .. }
322 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
323 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
324 tcx, parent,
325 )
326 .extend_to(tcx, def_id.to_def_id(), |param, _| {
327 tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
328 }),
329 };
330
331 let opaque_ty = Ty::new_opaque(tcx, ty::IsRigid::No, def_id.to_def_id(), args);
332
333 let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args).skip_norm_wip();
340 let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
341 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
342 _ => re,
343 });
344
345 for (predicate, pred_span) in tcx
349 .explicit_item_bounds(def_id)
350 .iter_instantiated_copied(tcx, args)
351 .map(Unnormalized::skip_norm_wip)
352 {
353 let predicate = predicate.fold_with(&mut BottomUpFolder {
354 tcx,
355 ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
356 lt_op: |lt| lt,
357 ct_op: |ct| ct,
358 });
359
360 ocx.register_obligation(Obligation::new(
361 tcx,
362 ObligationCause::new(
363 span,
364 def_id,
365 ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
366 ),
367 param_env,
368 predicate,
369 ));
370 }
371
372 let misc_cause = ObligationCause::misc(span, def_id);
373 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
377 Ok(()) => {}
378 Err(ty_err) => {
379 let ty_err = ty_err.to_string(tcx);
385 let guar = tcx.dcx().span_delayed_bug(
386 span,
387 format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
388 );
389 return Err(guar);
390 }
391 }
392
393 let predicate =
397 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
398 ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
399
400 let errors = ocx.evaluate_obligations_error_on_ambiguity();
403 if let TraitErrors::HasErrors(errors) = errors {
404 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
405 return Err(guar);
406 }
407
408 let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
415 ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
416
417 if infcx.next_trait_solver() {
418 Ok(())
419 } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
420 origin
421 {
422 let _ = infcx.take_opaque_types();
428 Ok(())
429 } else {
430 for (mut key, mut ty) in infcx.take_opaque_types() {
432 ty.ty = infcx.deeply_resolve_ignoring_regions(ty.ty);
433 key = infcx.deeply_resolve_ignoring_regions(key);
434 sanity_check_found_hidden_type(tcx, key, ty)?;
435 }
436 Ok(())
437 }
438}
439
440fn best_definition_site_of_opaque<'tcx>(
441 tcx: TyCtxt<'tcx>,
442 opaque_def_id: LocalDefId,
443 origin: hir::OpaqueTyOrigin<LocalDefId>,
444) -> Option<(Span, LocalDefId)> {
445 struct TaitConstraintLocator<'tcx> {
446 opaque_def_id: LocalDefId,
447 tcx: TyCtxt<'tcx>,
448 }
449 impl<'tcx> TaitConstraintLocator<'tcx> {
450 fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
451 if !self.tcx.has_typeck_results(item_def_id) {
452 return ControlFlow::Continue(());
453 }
454
455 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
456 if !opaque_types_defined_by.contains(&self.opaque_def_id) {
458 return ControlFlow::Continue(());
459 }
460
461 if let Some(hidden_ty) = self
462 .tcx
463 .mir_borrowck(item_def_id)
464 .ok()
465 .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
466 {
467 ControlFlow::Break((hidden_ty.span, item_def_id))
468 } else {
469 ControlFlow::Continue(())
470 }
471 }
472 }
473 impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
474 type NestedFilter = nested_filter::All;
475 type Result = ControlFlow<(Span, LocalDefId)>;
476 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
477 self.tcx
478 }
479 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
480 intravisit::walk_expr(self, ex)
481 }
482 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
483 self.check(it.owner_id.def_id)?;
484 intravisit::walk_item(self, it)
485 }
486 fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
487 self.check(it.owner_id.def_id)?;
488 intravisit::walk_impl_item(self, it)
489 }
490 fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
491 self.check(it.owner_id.def_id)?;
492 intravisit::walk_trait_item(self, it)
493 }
494 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
495 intravisit::walk_foreign_item(self, it)
496 }
497 }
498
499 let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
500 match origin {
501 hir::OpaqueTyOrigin::FnReturn { parent, .. }
502 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
503 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
504 let impl_def_id = tcx.local_parent(parent);
505 for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
506 match assoc.kind {
507 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
508 if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
509 {
510 return Some(span);
511 }
512 }
513 ty::AssocKind::Type { .. } => {}
514 }
515 }
516
517 None
518 }
519 hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
520 tcx.hir_walk_toplevel_module(&mut locator).break_value()
521 }
522 }
523}
524
525fn sanity_check_found_hidden_type<'tcx>(
526 tcx: TyCtxt<'tcx>,
527 key: ty::OpaqueTypeKey<'tcx>,
528 mut ty: ty::ProvisionalHiddenType<'tcx>,
529) -> Result<(), ErrorGuaranteed> {
530 if ty.ty.is_ty_var() {
531 return Ok(());
533 }
534 if let &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = ty.ty.kind() {
535 if def_id == key.def_id.to_def_id() && args == key.args {
536 return Ok(());
539 }
540 }
541 let erase_re_vars = |ty: Ty<'tcx>| {
542 fold_regions(tcx, ty, |r, _| match r.kind() {
543 RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
544 _ => r,
545 })
546 };
547 ty.ty = erase_re_vars(ty.ty);
550 let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args).skip_norm_wip();
552 let hidden_ty = erase_re_vars(hidden_ty);
553
554 if hidden_ty == ty.ty {
556 Ok(())
557 } else {
558 let span = tcx.def_span(key.def_id);
559 let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
560 Err(ty.build_mismatch_error(&other, tcx)?.emit())
561 }
562}
563
564fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
573 let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
574 let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
575 hir::GenericBound::Use(bounds, ..) => Some(bounds),
576 _ => None,
577 }) else {
578 return;
580 };
581
582 let mut expected_captures = UnordSet::default();
583 let mut shadowed_captures = UnordSet::default();
584 let mut seen_params = UnordMap::default();
585 let mut prev_non_lifetime_param = None;
586 for arg in precise_capturing_args {
587 let (hir_id, ident) = match *arg {
588 hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
589 hir_id,
590 ident,
591 ..
592 }) => {
593 if prev_non_lifetime_param.is_none() {
594 prev_non_lifetime_param = Some(ident);
595 }
596 (hir_id, ident)
597 }
598 hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
599 if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
600 tcx.dcx().emit_err(diagnostics::LifetimesMustBeFirst {
601 lifetime_span: ident.span,
602 name: ident.name,
603 other_span: prev_non_lifetime_param.span,
604 });
605 }
606 (hir_id, ident)
607 }
608 };
609
610 let ident = ident.normalize_to_macros_2_0();
611 if let Some(span) = seen_params.insert(ident, ident.span) {
612 tcx.dcx().emit_err(diagnostics::DuplicatePreciseCapture {
613 name: ident.name,
614 first_span: span,
615 second_span: ident.span,
616 });
617 }
618
619 match tcx.named_bound_var(hir_id) {
620 Some(ResolvedArg::EarlyBound(def_id)) => {
621 expected_captures.insert(def_id.to_def_id());
622
623 if let DefKind::LifetimeParam = tcx.def_kind(def_id)
629 && let Some(def_id) = tcx
630 .map_opaque_lifetime_to_parent_lifetime(def_id)
631 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
632 {
633 shadowed_captures.insert(def_id);
634 }
635 }
636 _ => {
637 tcx.dcx()
638 .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
639 }
640 }
641 }
642
643 let variances = tcx.variances_of(opaque_def_id);
644 let mut def_id = Some(opaque_def_id.to_def_id());
645 while let Some(generics) = def_id {
646 let generics = tcx.generics_of(generics);
647 def_id = generics.parent;
648
649 for param in &generics.own_params {
650 if expected_captures.contains(¶m.def_id) {
651 {
match (&variances[param.index as usize], &ty::Invariant) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("precise captured param should be invariant")));
}
}
}
};assert_eq!(
652 variances[param.index as usize],
653 ty::Invariant,
654 "precise captured param should be invariant"
655 );
656 continue;
657 }
658 if shadowed_captures.contains(¶m.def_id) {
662 continue;
663 }
664
665 match param.kind {
666 ty::GenericParamDefKind::Lifetime => {
667 let use_span = tcx.def_span(param.def_id);
668 let opaque_span = tcx.def_span(opaque_def_id);
669 if variances[param.index as usize] == ty::Invariant {
671 if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
672 && let Some(def_id) = tcx
673 .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
674 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
675 {
676 tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured {
677 opaque_span,
678 use_span,
679 param_span: tcx.def_span(def_id),
680 });
681 } else {
682 if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
683 tcx.dcx().emit_err(diagnostics::LifetimeImplicitlyCaptured {
684 opaque_span,
685 param_span: tcx.def_span(param.def_id),
686 });
687 } else {
688 tcx.dcx().emit_err(diagnostics::LifetimeNotCaptured {
693 opaque_span,
694 use_span: opaque_span,
695 param_span: use_span,
696 });
697 }
698 }
699 continue;
700 }
701 }
702 ty::GenericParamDefKind::Type { .. } => {
703 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(param.def_id) {
DefKind::Trait | DefKind::TraitAlias => true,
_ => false,
}matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {
704 tcx.dcx().emit_err(diagnostics::SelfTyNotCaptured {
706 trait_span: tcx.def_span(param.def_id),
707 opaque_span: tcx.def_span(opaque_def_id),
708 });
709 } else {
710 tcx.dcx().emit_err(diagnostics::ParamNotCaptured {
712 param_span: tcx.def_span(param.def_id),
713 opaque_span: tcx.def_span(opaque_def_id),
714 kind: "type",
715 });
716 }
717 }
718 ty::GenericParamDefKind::Const { .. } => {
719 tcx.dcx().emit_err(diagnostics::ParamNotCaptured {
721 param_span: tcx.def_span(param.def_id),
722 opaque_span: tcx.def_span(opaque_def_id),
723 kind: "const",
724 });
725 }
726 }
727 }
728 }
729}
730
731fn is_enum_of_nonnullable_ptr<'tcx>(
732 tcx: TyCtxt<'tcx>,
733 adt_def: AdtDef<'tcx>,
734 args: GenericArgsRef<'tcx>,
735) -> bool {
736 if adt_def.repr().inhibit_enum_layout_opt() {
737 return false;
738 }
739
740 let [var_one, var_two] = &adt_def.variants().raw[..] else {
741 return false;
742 };
743 let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
744 return false;
745 };
746 #[allow(non_exhaustive_omitted_patterns)] match field.ty(tcx,
args).skip_norm_wip().kind() {
ty::FnPtr(..) | ty::Ref(..) => true,
_ => false,
}matches!(field.ty(tcx, args).skip_norm_wip().kind(), ty::FnPtr(..) | ty::Ref(..))
747}
748
749fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
750 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
751 if match tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
752 ty::RawPtr(_, _) => false,
753 ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
754 _ => true,
755 } {
756 tcx.dcx().emit_err(diagnostics::LinkageType { span: tcx.def_span(def_id) });
757 }
758 }
759}
760
761pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
762 let mut res = Ok(());
763 let generics = tcx.generics_of(def_id);
764
765 for param in &generics.own_params {
766 match param.kind {
767 ty::GenericParamDefKind::Lifetime { .. } => {}
768 ty::GenericParamDefKind::Type { has_default, .. } => {
769 if has_default {
770 tcx.ensure_ok().type_of(param.def_id);
771 }
772 }
773 ty::GenericParamDefKind::Const { has_default, .. } => {
774 tcx.ensure_ok().type_of(param.def_id);
775 if has_default {
776 let ct = tcx.const_param_default(param.def_id).skip_binder();
778 if let ty::ConstKind::Alias(_, alias_const) = ct.kind()
779 && let Some(def_id) = alias_const.kind.opt_def_id()
780 {
781 tcx.ensure_ok().type_of(def_id);
782 }
783 }
784 }
785 }
786 }
787
788 match tcx.def_kind(def_id) {
789 DefKind::Static { .. } => {
790 tcx.ensure_ok().generics_of(def_id);
791 tcx.ensure_ok().type_of(def_id);
792 tcx.ensure_ok().clauses_of(def_id);
793
794 check_static_inhabited(tcx, def_id);
795 check_static_linkage(tcx, def_id);
796 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
797 res = res.and(wfcheck::check_static_item(
798 tcx, def_id, ty, true,
799 ));
800
801 return res;
805 }
806 DefKind::Enum => {
807 tcx.ensure_ok().generics_of(def_id);
808 tcx.ensure_ok().type_of(def_id);
809 tcx.ensure_ok().clauses_of(def_id);
810 crate::collect::check_enum_variant_types(tcx, def_id);
811 check_enum(tcx, def_id);
812 check_variances_for_type_defn(tcx, def_id);
813 res = res.and(check_type_defn(tcx, def_id, true));
814 return res;
816 }
817 DefKind::Fn => {
818 tcx.ensure_ok().generics_of(def_id);
819 tcx.ensure_ok().type_of(def_id);
820 tcx.ensure_ok().clauses_of(def_id);
821 tcx.ensure_ok().fn_sig(def_id);
822 tcx.ensure_ok().codegen_fn_attrs(def_id);
823 if let Some(i) = tcx.intrinsic(def_id) {
824 intrinsic::check_intrinsic_type(
825 tcx,
826 def_id,
827 tcx.def_ident_span(def_id).unwrap(),
828 i.name,
829 )
830 }
831 }
832 DefKind::Impl { of_trait } => {
833 tcx.ensure_ok().generics_of(def_id);
834 tcx.ensure_ok().type_of(def_id);
835 tcx.ensure_ok().clauses_of(def_id);
836 tcx.ensure_ok().associated_items(def_id);
837 if of_trait {
838 let impl_trait_header = tcx.impl_trait_header(def_id);
839 res = res
840 .and(tcx.ensure_result().coherent_trait(impl_trait_header.trait_ref.def_id()));
841
842 if res.is_ok() {
843 check_impl_items_against_trait(tcx, def_id, impl_trait_header);
847 }
848 }
849 }
850 DefKind::Trait => {
851 tcx.ensure_ok().generics_of(def_id);
852 tcx.ensure_ok().trait_def(def_id);
853 tcx.ensure_ok().explicit_super_clauses_of(def_id);
854 tcx.ensure_ok().clauses_of(def_id);
855 tcx.ensure_ok().associated_items(def_id);
856 let assoc_items = tcx.associated_items(def_id);
857
858 for &assoc_item in assoc_items.in_definition_order() {
859 match assoc_item.kind {
860 ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
861 let trait_args = GenericArgs::identity_for_item(tcx, def_id);
862 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
863 tcx,
864 assoc_item,
865 assoc_item,
866 ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
867 );
868 }
869 ty::AssocKind::Const { .. } if assoc_item.defaultness(tcx).has_value() => {
870 let _: Result<_, rustc_errors::ErrorGuaranteed> =
871 super::compare_impl_item::compare_const_directness(
872 tcx, assoc_item, assoc_item,
873 );
874 }
875 _ => {}
876 }
877 }
878 res = res.and(wfcheck::check_trait(tcx, def_id));
879 wfcheck::check_gat_where_clauses(tcx, def_id);
880 return res;
882 }
883 DefKind::TraitAlias => {
884 tcx.ensure_ok().generics_of(def_id);
885 tcx.ensure_ok().explicit_implied_clauses_of(def_id);
886 tcx.ensure_ok().explicit_super_clauses_of(def_id);
887 tcx.ensure_ok().clauses_of(def_id);
888 res = res.and(wfcheck::check_trait(tcx, def_id));
889 return res;
891 }
892 def_kind @ (DefKind::Struct | DefKind::Union) => {
893 tcx.ensure_ok().generics_of(def_id);
894 tcx.ensure_ok().type_of(def_id);
895 tcx.ensure_ok().clauses_of(def_id);
896
897 let adt = tcx.adt_def(def_id).non_enum_variant();
898 for f in adt.fields.iter() {
899 tcx.ensure_ok().generics_of(f.did);
900 tcx.ensure_ok().type_of(f.did);
901 tcx.ensure_ok().clauses_of(f.did);
902 }
903
904 if let Some((_, ctor_def_id)) = adt.ctor {
905 crate::collect::check_ctor(tcx, ctor_def_id.expect_local());
906 }
907 check_variances_for_type_defn(tcx, def_id);
908 res = res.and(match def_kind {
909 DefKind::Struct => check_struct(tcx, def_id),
910 DefKind::Union => check_union(tcx, def_id),
911 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
912 });
913 return res;
915 }
916 DefKind::OpaqueTy => {
917 check_opaque_precise_captures(tcx, def_id);
918
919 let origin = tcx.local_opaque_ty_origin(def_id);
920 if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
921 | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
922 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
923 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
924 {
925 } else {
927 check_opaque(tcx, def_id);
928 }
929
930 tcx.ensure_ok().clauses_of(def_id);
931 tcx.ensure_ok().explicit_item_bounds(def_id);
932 tcx.ensure_ok().explicit_item_self_bounds(def_id);
933 if tcx.is_conditionally_const(def_id) {
934 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
935 tcx.ensure_ok().const_conditions(def_id);
936 }
937
938 return res;
942 }
943 DefKind::Const => {
944 tcx.ensure_ok().generics_of(def_id);
945 tcx.ensure_ok().type_of(def_id);
946 tcx.ensure_ok().clauses_of(def_id);
947
948 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
949 let ty = tcx.type_of(def_id).instantiate_identity();
950 let ty_span = tcx.ty_span(def_id);
951 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
952 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
953 wfcx.register_bound(
954 traits::ObligationCause::new(
955 ty_span,
956 def_id,
957 ObligationCauseCode::SizedConstOrStatic,
958 ),
959 tcx.param_env(def_id),
960 ty,
961 tcx.require_lang_item(LangItem::Sized, ty_span),
962 );
963 check_where_clauses(wfcx, def_id);
964 wfcheck::check_const_item(wfcx, def_id, ty);
965 Ok(())
966 }));
967
968 return res;
972 }
973 DefKind::TyAlias => {
974 tcx.ensure_ok().generics_of(def_id);
975 tcx.ensure_ok().type_of(def_id);
976 tcx.ensure_ok().clauses_of(def_id);
977 let ty = tcx.type_of(def_id).instantiate_identity();
978 let span = tcx.def_span(def_id);
979 if tcx.type_alias_is_checked(def_id) {
980 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
981 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
982 wfcx.register_wf_obligation(
983 span,
984 Some(WellFormedLoc::Ty(def_id)),
985 item_ty.into(),
986 );
987 check_where_clauses(wfcx, def_id);
988 Ok(())
989 }));
990 } else {
991 check_type_alias_type_params_are_used(tcx, def_id);
992 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
993 if let Some(unnormalized_obligations) = wfcx.unnormalized_obligations(span, ty.skip_norm_wip())
1004 {
1005 let filtered_obligations =
1006 unnormalized_obligations.into_iter().filter(|o| {
1007 #[allow(non_exhaustive_omitted_patterns)] match o.predicate.kind().skip_binder()
{
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _)) if
#[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
} => true,
_ => false,
}matches!(o.predicate.kind().skip_binder(),
1008 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
1009 if matches!(ct.kind(), ty::ConstKind::Param(..)))
1010 });
1011 wfcx.ocx.register_obligations(filtered_obligations)
1012 }
1013 Ok(())
1014 }));
1015 }
1016
1017 return res;
1021 }
1022 DefKind::ForeignMod => {
1023 let it = tcx.hir_expect_item(def_id);
1024 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
1025 return Ok(());
1026 };
1027
1028 check_abi(tcx, it.hir_id(), it.span, abi);
1029
1030 for &item in items {
1031 let def_id = item.owner_id.def_id;
1032
1033 let generics = tcx.generics_of(def_id);
1034 let own_counts = generics.own_counts();
1035 if generics.own_params.len() - own_counts.lifetimes != 0 {
1036 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
1037 (_, 0) => ("type", "types", Some("u32")),
1038 (0, _) => ("const", "consts", None),
1041 _ => ("type or const", "types or consts", None),
1042 };
1043 let name = if {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcEiiForeignItem) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def_id, RustcEiiForeignItem) {
1044 "externally implementable items"
1045 } else {
1046 "foreign items"
1047 };
1048
1049 let span = tcx.def_span(def_id);
1050 {
tcx.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} may not have {1} parameters",
name, kinds))
})).with_code(E0044)
}struct_span_code_err!(
1051 tcx.dcx(),
1052 span,
1053 E0044,
1054 "{name} may not have {kinds} parameters",
1055 )
1056 .with_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("can\'t have {0} parameters",
kinds))
})format!("can't have {kinds} parameters"))
1057 .with_help(
1058 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("replace the {0} parameters with concrete {1}{2}",
kinds, kinds_pl,
egs.map(|egs|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" like `{0}`", egs))
})).unwrap_or_default()))
})format!(
1061 "replace the {} parameters with concrete {}{}",
1062 kinds,
1063 kinds_pl,
1064 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
1065 ),
1066 )
1067 .emit();
1068 }
1069
1070 tcx.ensure_ok().generics_of(def_id);
1071 tcx.ensure_ok().type_of(def_id);
1072 tcx.ensure_ok().clauses_of(def_id);
1073 if tcx.is_conditionally_const(def_id) {
1074 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1075 tcx.ensure_ok().const_conditions(def_id);
1076 }
1077 match tcx.def_kind(def_id) {
1078 DefKind::Fn => {
1079 tcx.ensure_ok().codegen_fn_attrs(def_id);
1080 tcx.ensure_ok().fn_sig(def_id);
1081 let item = tcx.hir_foreign_item(item);
1082 let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!() };
1083 check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1084 }
1085 DefKind::Static { .. } => {
1086 tcx.ensure_ok().codegen_fn_attrs(def_id);
1087 }
1088 _ => (),
1089 }
1090 }
1091 return res;
1093 }
1094 DefKind::Closure => {
1095 tcx.ensure_ok().codegen_fn_attrs(def_id);
1099 return res;
1107 }
1108 DefKind::AssocFn => {
1109 tcx.ensure_ok().codegen_fn_attrs(def_id);
1110 tcx.ensure_ok().type_of(def_id);
1111 tcx.ensure_ok().fn_sig(def_id);
1112 tcx.ensure_ok().clauses_of(def_id);
1113 res = res.and(check_associated_item(tcx, def_id));
1114 let assoc_item = tcx.associated_item(def_id);
1115 match assoc_item.container {
1116 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1117 ty::AssocContainer::Trait => {
1118 res = res.and(check_trait_item(tcx, def_id));
1119 }
1120 }
1121
1122 return res;
1126 }
1127 DefKind::AssocConst => {
1128 tcx.ensure_ok().type_of(def_id);
1129 tcx.ensure_ok().clauses_of(def_id);
1130 res = res.and(check_associated_item(tcx, def_id));
1131 let assoc_item = tcx.associated_item(def_id);
1132 match assoc_item.container {
1133 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1134 ty::AssocContainer::Trait => {
1135 res = res.and(check_trait_item(tcx, def_id));
1136 }
1137 }
1138
1139 return res;
1143 }
1144 DefKind::AssocTy => {
1145 tcx.ensure_ok().clauses_of(def_id);
1146 res = res.and(check_associated_item(tcx, def_id));
1147
1148 let assoc_item = tcx.associated_item(def_id);
1149 let has_type = match assoc_item.container {
1150 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1151 ty::AssocContainer::Trait => {
1152 tcx.ensure_ok().explicit_item_bounds(def_id);
1153 tcx.ensure_ok().explicit_item_self_bounds(def_id);
1154 if tcx.is_conditionally_const(def_id) {
1155 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1156 tcx.ensure_ok().const_conditions(def_id);
1157 }
1158 res = res.and(check_trait_item(tcx, def_id));
1159 assoc_item.defaultness(tcx).has_value()
1160 }
1161 };
1162 if has_type {
1163 tcx.ensure_ok().type_of(def_id);
1164 }
1165
1166 return res;
1170 }
1171 DefKind::TestBinderConstraints => {
1172 tcx.ensure_ok().generics_of(def_id);
1173 tcx.ensure_ok().clauses_of(def_id);
1174 let (_, body) =
1175 tcx.hir_node_by_def_id(def_id).expect_item().expect_test_binder_constraints();
1176 let icx = ItemCtxt::new(tcx, def_id);
1177 let lowered = icx.lower_test_binder_body(body);
1178 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1179 wfcx.check_test_binder_body(lowered);
1180 Ok(())
1181 }));
1182 return res;
1183 }
1184
1185 DefKind::AnonConst
1187 | DefKind::ExternCrate
1188 | DefKind::Macro(..)
1189 | DefKind::Use
1190 | DefKind::GlobalAsm
1191 | DefKind::Mod => return res,
1192
1193 DefKind::ForeignTy => {}
1194
1195 DefKind::Variant
1196 | DefKind::TyParam
1197 | DefKind::ConstParam
1198 | DefKind::Ctor(..)
1199 | DefKind::Field
1200 | DefKind::LifetimeParam
1201 | DefKind::SyntheticCoroutineBody => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{1:?}: {0:?}", tcx.def_kind(def_id), def_id)));
}unreachable!("{def_id:?}: {:?}", tcx.def_kind(def_id)),
1202 }
1203 let node = tcx.hir_node_by_def_id(def_id);
1204 res.and(match node {
1205 hir::Node::Crate(_) => bug_impl(None,
format_args!("check_well_formed cannot be applied to the crate root"),
Location::caller())bug!("check_well_formed cannot be applied to the crate root"),
1206 hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1207 hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1208 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", node)));
}unreachable!("{node:?}"),
1209 })
1210}
1211
1212fn check_specialization_validity<'tcx>(
1213 tcx: TyCtxt<'tcx>,
1214 trait_def: &ty::TraitDef,
1215 trait_item: ty::AssocItem,
1216 impl_id: DefId,
1217 impl_item: DefId,
1218) {
1219 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1220 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1221 if parent.is_from_trait() {
1222 None
1223 } else {
1224 Some((parent, parent.item(tcx, trait_item.def_id)))
1225 }
1226 });
1227
1228 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1229 match parent_item {
1230 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1233 Some(Err(parent_impl.def_id()))
1234 }
1235
1236 Some(_) => Some(Ok(())),
1238
1239 None => {
1243 if tcx.defaultness(parent_impl.def_id()).is_default() {
1244 None
1245 } else {
1246 Some(Err(parent_impl.def_id()))
1247 }
1248 }
1249 }
1250 });
1251
1252 let result = opt_result.unwrap_or(Ok(()));
1255
1256 if let Err(parent_impl) = result {
1257 if !tcx.is_impl_trait_in_trait(impl_item) {
1258 let span = tcx.def_span(impl_item);
1259 let ident = tcx.item_ident(impl_item);
1260
1261 let err = match tcx.span_of_impl(parent_impl) {
1262 Ok(sp) => diagnostics::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp },
1263 Err(cname) => diagnostics::ImplNotMarkedDefault::Err { span, ident, cname },
1264 };
1265
1266 tcx.dcx().emit_err(err);
1267 } else {
1268 tcx.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("parent item: {0:?} not marked as default",
parent_impl))
})format!("parent item: {parent_impl:?} not marked as default"));
1269 }
1270 }
1271}
1272
1273fn check_overriding_final_trait_item<'tcx>(
1274 tcx: TyCtxt<'tcx>,
1275 trait_item: ty::AssocItem,
1276 impl_item: ty::AssocItem,
1277) {
1278 if trait_item.is_fn() && trait_item.defaultness(tcx).is_final() {
1279 tcx.dcx().emit_err(diagnostics::OverridingFinalTraitFunction {
1280 impl_span: tcx.def_span(impl_item.def_id),
1281 trait_span: tcx.def_span(trait_item.def_id),
1282 ident: tcx.item_ident(impl_item.def_id),
1283 });
1284 }
1285}
1286
1287fn check_impl_items_against_trait<'tcx>(
1288 tcx: TyCtxt<'tcx>,
1289 impl_id: LocalDefId,
1290 impl_trait_header: ty::ImplTraitHeader<'tcx>,
1291) {
1292 let trait_ref = impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip();
1293 if trait_ref.references_error() {
1297 return;
1298 }
1299
1300 let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1301
1302 match impl_trait_header.polarity {
1304 ty::ImplPolarity::Positive => {}
1305 ty::ImplPolarity::Negative => {
1306 if let [first_item_ref, ..] = *impl_item_refs {
1307 let first_item_span = tcx.def_span(first_item_ref);
1308 {
tcx.dcx().struct_span_err(first_item_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("negative impls cannot have any items"))
})).with_code(E0749)
}struct_span_code_err!(
1309 tcx.dcx(),
1310 first_item_span,
1311 E0749,
1312 "negative impls cannot have any items"
1313 )
1314 .emit();
1315 }
1316 return;
1317 }
1318 }
1319
1320 let trait_def = tcx.trait_def(trait_ref.def_id);
1321
1322 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1323
1324 for &impl_item in impl_item_refs {
1325 let ty_impl_item = tcx.associated_item(impl_item);
1326 let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1327 Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1328 Err(ErrorGuaranteed { .. }) => continue,
1329 };
1330
1331 let res = tcx.ensure_result().compare_impl_item(impl_item.expect_local());
1332 if res.is_ok() {
1333 match ty_impl_item.kind {
1334 ty::AssocKind::Fn { .. } => {
1335 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1336 tcx,
1337 ty_impl_item,
1338 ty_trait_item,
1339 tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1340 .instantiate_identity()
1341 .skip_norm_wip(),
1342 );
1343 }
1344 ty::AssocKind::Const { .. } => {}
1345 ty::AssocKind::Type { .. } => {}
1346 }
1347 }
1348
1349 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1350 tcx.emit_node_span_lint(
1351 DEAD_CODE,
1352 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1353 tcx.def_span(ty_impl_item.def_id),
1354 diagnostics::UselessImplItem,
1355 )
1356 }
1357
1358 check_specialization_validity(
1359 tcx,
1360 trait_def,
1361 ty_trait_item,
1362 impl_id.to_def_id(),
1363 impl_item,
1364 );
1365
1366 check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item);
1367 }
1368
1369 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1370 let mut missing_items = Vec::new();
1372
1373 let mut must_implement_one_of: Option<&[Ident]> =
1374 trait_def.must_implement_one_of.as_deref();
1375
1376 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1377 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1378
1379 let is_implemented = leaf_def
1380 .as_ref()
1381 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1382
1383 if !is_implemented
1384 && tcx.defaultness(impl_id).is_final()
1385 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1387 {
1388 missing_items.push(tcx.associated_item(trait_item_id));
1389 }
1390
1391 let is_implemented_here =
1393 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1394
1395 if !is_implemented_here {
1396 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1397 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1398 EvalResult::Deny { .. }
1401 if !tcx.features().pin_ergonomics()
1402 && tcx.is_lang_item(trait_ref.def_id, LangItem::Drop)
1403 && tcx.item_name(trait_item_id) == sym::drop =>
1404 {
1405 missing_items.push(tcx.associated_item(trait_item_id));
1406 }
1407 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1408 tcx,
1409 full_impl_span,
1410 trait_item_id,
1411 feature,
1412 reason,
1413 issue,
1414 ),
1415
1416 EvalResult::Allow | EvalResult::Unmarked => {}
1418 }
1419 }
1420
1421 if let Some(required_items) = &must_implement_one_of {
1422 if is_implemented_here {
1423 let trait_item = tcx.associated_item(trait_item_id);
1424 if required_items.contains(&trait_item.ident(tcx)) {
1425 must_implement_one_of = None;
1426 }
1427 }
1428 }
1429
1430 if let Some(leaf_def) = &leaf_def
1431 && !leaf_def.is_final()
1432 && let def_id = leaf_def.item.def_id
1433 && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1434 {
1435 let def_kind = tcx.def_kind(def_id);
1436 let descr = tcx.def_kind_descr(def_kind, def_id);
1437 let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1438 (
1439 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("async {0} in trait cannot be specialized",
descr))
})format!("async {descr} in trait cannot be specialized"),
1440 "async functions in traits",
1441 )
1442 } else {
1443 (
1444 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} with return-position `impl Trait` in trait cannot be specialized",
descr))
})format!(
1445 "{descr} with return-position `impl Trait` in trait cannot be specialized"
1446 ),
1447 "return position `impl Trait` in traits",
1448 )
1449 };
1450 tcx.dcx()
1451 .struct_span_err(tcx.def_span(def_id), msg)
1452 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("specialization behaves in inconsistent and surprising ways with {0}, and for now is disallowed",
feature))
})format!(
1453 "specialization behaves in inconsistent and surprising ways with \
1454 {feature}, and for now is disallowed"
1455 ))
1456 .emit();
1457 }
1458 }
1459
1460 if !missing_items.is_empty() {
1461 missing_items_err(tcx, impl_id, &missing_items);
1462 }
1463
1464 if let Some(missing_items) = must_implement_one_of {
1465 let attr_span = {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(trait_ref.def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcMustImplementOneOf {
attr_span, .. }) => {
break 'done Some(*attr_span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, trait_ref.def_id, RustcMustImplementOneOf {attr_span, ..} => *attr_span);
1466 let missing_items = missing_items.into_iter().map(|i| i.name);
1467 missing_items_must_implement_one_of_err(tcx, impl_id, missing_items, attr_span);
1468 }
1469 }
1470}
1471
1472fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1473 let t = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1474 if let ty::Adt(def, args) = t.kind()
1475 && def.is_struct()
1476 {
1477 let fields = &def.non_enum_variant().fields;
1478 if fields.is_empty() {
1479 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("SIMD vector cannot be empty"))
})).with_code(E0075)
}struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1480 return;
1481 }
1482
1483 let array_field = &fields[FieldIdx::ZERO];
1484 let array_ty = array_field.ty(tcx, args).skip_norm_wip();
1485 let ty::Array(element_ty, len_const) = array_ty.kind() else {
1486 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("SIMD vector\'s only field must be an array"))
})).with_code(E0076)
}struct_span_code_err!(
1487 tcx.dcx(),
1488 sp,
1489 E0076,
1490 "SIMD vector's only field must be an array"
1491 )
1492 .with_span_label(tcx.def_span(array_field.did), "not an array")
1493 .emit();
1494 return;
1495 };
1496
1497 if let Some(second_field) = fields.get(FieldIdx::ONE) {
1498 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("SIMD vector cannot have multiple fields"))
})).with_code(E0075)
}struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1499 .with_span_label(tcx.def_span(second_field.did), "excess field")
1500 .emit();
1501 return;
1502 }
1503
1504 if let Some(len) = len_const.try_to_target_usize(tcx) {
1509 if len == 0 {
1510 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("SIMD vector cannot be empty"))
})).with_code(E0075)
}struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1511 return;
1512 } else if len > MAX_SIMD_LANES.into() {
1513 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("SIMD vector cannot have more than {0} elements",
MAX_SIMD_LANES))
})).with_code(E0075)
}struct_span_code_err!(
1514 tcx.dcx(),
1515 sp,
1516 E0075,
1517 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1518 )
1519 .emit();
1520 return;
1521 }
1522 }
1523
1524 match element_ty.kind() {
1529 ty::Param(_) => (), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), _ => {
1532 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("SIMD vector element type should be a primitive scalar (integer/float/pointer) type"))
})).with_code(E0077)
}struct_span_code_err!(
1533 tcx.dcx(),
1534 sp,
1535 E0077,
1536 "SIMD vector element type should be a \
1537 primitive scalar (integer/float/pointer) type"
1538 )
1539 .emit();
1540 return;
1541 }
1542 }
1543 }
1544}
1545
1546{}
#[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_scalable_vector",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(1546u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
::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("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("scalable")
}> =
::tracing::__macro_support::FieldName::new("scalable");
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(&def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalable)
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: () = loop {};
return __tracing_attr_fake_return;
}
{
let ty =
tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
let ty::Adt(def, args) = ty.kind() else { return };
if !def.is_struct() {
tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
return;
}
let fields = &def.non_enum_variant().fields;
match scalable {
ScalableElt::ElementCount(..) if fields.is_empty() => {
let mut err =
tcx.dcx().struct_span_err(span,
"scalable vectors must have a single field");
err.help("scalable vector types' only field must be a primitive scalar type");
err.emit();
return;
}
ScalableElt::ElementCount(..) if fields.len() >= 2 => {
tcx.dcx().span_err(span,
"scalable vectors cannot have multiple fields");
return;
}
ScalableElt::Container if fields.is_empty() => {
let mut err =
tcx.dcx().struct_span_err(span,
"scalable vector tuples must have at least one field");
err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
err.emit();
return;
}
ScalableElt::Container if fields.len() > 8 => {
let mut err =
tcx.dcx().struct_span_err(span,
"scalable vector tuples can have at most eight fields");
err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
err.emit();
return;
}
_ => {}
}
match scalable {
ScalableElt::ElementCount(..) => {
let element_ty =
&fields[FieldIdx::ZERO].ty(tcx, args).skip_norm_wip();
match element_ty.kind() {
ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
_ => {
let mut err =
tcx.dcx().struct_span_err(span,
"element type of a scalable vector must be a primitive scalar");
err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
err.emit();
}
}
}
ScalableElt::Container => {
let mut prev_field_ty = None;
for field in fields.iter() {
let element_ty = field.ty(tcx, args).skip_norm_wip();
if let ty::Adt(def, _) = element_ty.kind() &&
def.repr().scalable() {
match def.repr().scalable.expect("`repr().scalable.is_some()` != `repr().scalable()`")
{
ScalableElt::ElementCount(_) => {}
ScalableElt::Container => {
tcx.dcx().span_err(tcx.def_span(field.did),
"scalable vector structs cannot contain other scalable vector structs");
break;
}
}
} else {
tcx.dcx().span_err(tcx.def_span(field.did),
"scalable vector structs can only have scalable vector fields");
break;
}
if let Some(prev_ty) = prev_field_ty.replace(element_ty) &&
prev_ty != element_ty {
tcx.dcx().span_err(tcx.def_span(field.did),
"all fields in a scalable vector struct must be the same type");
break;
}
}
}
}
}
}
}#[tracing::instrument(skip(tcx), level = "debug")]
1547fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {
1548 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1549 let ty::Adt(def, args) = ty.kind() else { return };
1550 if !def.is_struct() {
1551 tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
1552 return;
1553 }
1554
1555 let fields = &def.non_enum_variant().fields;
1556 match scalable {
1557 ScalableElt::ElementCount(..) if fields.is_empty() => {
1558 let mut err =
1559 tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1560 err.help("scalable vector types' only field must be a primitive scalar type");
1561 err.emit();
1562 return;
1563 }
1564 ScalableElt::ElementCount(..) if fields.len() >= 2 => {
1565 tcx.dcx().span_err(span, "scalable vectors cannot have multiple fields");
1566 return;
1567 }
1568 ScalableElt::Container if fields.is_empty() => {
1569 let mut err = tcx
1570 .dcx()
1571 .struct_span_err(span, "scalable vector tuples must have at least one field");
1572 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1573 err.emit();
1574 return;
1575 }
1576 ScalableElt::Container if fields.len() > 8 => {
1577 let mut err = tcx
1578 .dcx()
1579 .struct_span_err(span, "scalable vector tuples can have at most eight fields");
1580 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1581 err.emit();
1582 return;
1583 }
1584 _ => {}
1585 }
1586
1587 match scalable {
1588 ScalableElt::ElementCount(..) => {
1589 let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args).skip_norm_wip();
1590
1591 match element_ty.kind() {
1595 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
1596 _ => {
1597 let mut err = tcx.dcx().struct_span_err(
1598 span,
1599 "element type of a scalable vector must be a primitive scalar",
1600 );
1601 err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
1602 err.emit();
1603 }
1604 }
1605 }
1606 ScalableElt::Container => {
1607 let mut prev_field_ty = None;
1608 for field in fields.iter() {
1609 let element_ty = field.ty(tcx, args).skip_norm_wip();
1610 if let ty::Adt(def, _) = element_ty.kind()
1611 && def.repr().scalable()
1612 {
1613 match def
1614 .repr()
1615 .scalable
1616 .expect("`repr().scalable.is_some()` != `repr().scalable()`")
1617 {
1618 ScalableElt::ElementCount(_) => { }
1619 ScalableElt::Container => {
1620 tcx.dcx().span_err(
1621 tcx.def_span(field.did),
1622 "scalable vector structs cannot contain other scalable vector structs",
1623 );
1624 break;
1625 }
1626 }
1627 } else {
1628 tcx.dcx().span_err(
1629 tcx.def_span(field.did),
1630 "scalable vector structs can only have scalable vector fields",
1631 );
1632 break;
1633 }
1634
1635 if let Some(prev_ty) = prev_field_ty.replace(element_ty)
1636 && prev_ty != element_ty
1637 {
1638 tcx.dcx().span_err(
1639 tcx.def_span(field.did),
1640 "all fields in a scalable vector struct must be the same type",
1641 );
1642 break;
1643 }
1644 }
1645 }
1646 }
1647}
1648
1649fn check_packed(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1650 let def = tcx.adt_def(def_id);
1651 let repr = def.repr();
1652 if repr.packed() {
1653 if def.is_pin_project() {
1657 tcx.dcx().emit_err(diagnostics::PinV2OnPacked {
1658 span: sp,
1659 pin_v2_span: {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def.did(), &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(PinV2(span)) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def.did(), PinV2(span) => *span),
1660 adt_name: tcx.item_name(def.did()),
1661 });
1662 }
1663 if let Some(reprs) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def.did(), &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Repr { reprs, .. }) => {
break 'done Some(reprs);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def.did(), Repr { reprs, .. } => reprs) {
1664 for (r, _) in reprs {
1665 if let ReprPacked(pack) = r
1666 && let Some(repr_pack) = repr.pack
1667 && pack != &repr_pack
1668 {
1669 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type has conflicting packed representation hints"))
})).with_code(E0634)
}struct_span_code_err!(
1670 tcx.dcx(),
1671 sp,
1672 E0634,
1673 "type has conflicting packed representation hints"
1674 )
1675 .emit();
1676 }
1677 }
1678 }
1679
1680 if repr.align.is_some() {
1681 {
tcx.dcx().struct_span_err(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type has conflicting packed and align representation hints"))
})).with_code(E0587)
}struct_span_code_err!(
1682 tcx.dcx(),
1683 sp,
1684 E0587,
1685 "type has conflicting packed and align representation hints"
1686 )
1687 .emit();
1688 } else if repr.c()
1689 && let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut ::alloc::vec::Vec::new()vec![])
1690 {
1691 tcx.emit_node_span_lint(
1692 ALIGNED_FIELDS_IN_PACKED,
1693 tcx.local_def_id_to_hir_id(def_id),
1694 sp,
1695 rustc_errors::DiagDecorator(|diag| {
1696 diag.primary_message(
1697 "packed type cannot transitively contain a `#[repr(align)]` type",
1698 );
1699
1700 diag.span_note(
1701 tcx.def_span(def_spans[0].0),
1702 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has a `#[repr(align)]` attribute",
tcx.item_name(def_spans[0].0)))
})format!(
1703 "`{}` has a `#[repr(align)]` attribute",
1704 tcx.item_name(def_spans[0].0)
1705 ),
1706 );
1707
1708 if def_spans.len() <= 2 {
1709 return;
1712 }
1713
1714 let mut first = true;
1715 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1716 let ident = tcx.item_name(*adt_def);
1717 diag.span_note(
1718 *span,
1719 if first {
1720 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` contains a field of type `{1}`",
tcx.type_of(def.did()).instantiate_identity().skip_norm_wip(),
ident))
})format!(
1721 "`{}` contains a field of type `{}`",
1722 tcx.type_of(def.did()).instantiate_identity().skip_norm_wip(),
1723 ident
1724 )
1725 } else {
1726 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...which contains a field of type `{0}`",
ident))
})format!("...which contains a field of type `{ident}`")
1727 },
1728 );
1729 first = false;
1730 }
1731 }),
1732 );
1733 }
1734 }
1735}
1736
1737fn check_packed_inner(
1738 tcx: TyCtxt<'_>,
1739 def_id: DefId,
1740 stack: &mut Vec<DefId>,
1741) -> Option<Vec<(DefId, Span)>> {
1742 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
1743 if def.repr().c() && (def.is_struct() || def.is_union()) {
1744 if def.repr().align.is_some() {
1745 return Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(def.did(), DUMMY_SP)]))vec![(def.did(), DUMMY_SP)]);
1746 }
1747
1748 stack.push(def_id);
1749 for field in &def.non_enum_variant().fields {
1750 if let ty::Adt(def, _) = field.ty(tcx, args).skip_norm_wip().kind()
1751 && !stack.contains(&def.did())
1752 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1753 {
1754 defs.push((def.did(), field.ident(tcx).span));
1755 return Some(defs);
1756 }
1757 }
1758 stack.pop();
1759 }
1760 }
1761
1762 None
1763}
1764
1765fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1766 if !adt.repr().transparent() {
1767 return;
1768 }
1769
1770 if adt.is_union() && !tcx.features().transparent_unions() {
1771 feature_err(
1772 &tcx.sess,
1773 sym::transparent_unions,
1774 tcx.def_span(adt.did()),
1775 "transparent unions are unstable",
1776 )
1777 .emit();
1778 }
1779
1780 if adt.variants().len() != 1 {
1781 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1782 return;
1784 }
1785 let variant = adt.variant(VariantIdx::ZERO);
1786
1787 if variant.fields.len() <= 1 {
1788 return;
1790 }
1791
1792 let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1793
1794 enum NonTrivialReason<'tcx> {
1798 UnknownLayout,
1799 NonZeroSized,
1800 NonTrivialAlignment,
1801 PrivateField { inside: Ty<'tcx> },
1802 NonExhaustive { ty: Ty<'tcx> },
1803 ReprC { ty: Ty<'tcx> },
1804 }
1805 struct NonTrivialFieldInfo<'tcx> {
1806 span: Span,
1807 reason: NonTrivialReason<'tcx>,
1808 }
1809
1810 fn is_trivial<'tcx>(
1813 tcx: TyCtxt<'tcx>,
1814 typing_env: ty::TypingEnv<'tcx>,
1815 ty: Ty<'tcx>,
1816 ) -> ControlFlow<NonTrivialReason<'tcx>> {
1817 let ty =
1819 tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
1820 match ty.kind() {
1821 ty::Tuple(list) => list.iter().try_for_each(|t| is_trivial(tcx, typing_env, t)),
1822 ty::Array(ty, _) => is_trivial(tcx, typing_env, *ty),
1823 ty::Adt(def, args) => {
1824 if !def.did().is_local() && !{
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def.did(), &tcx)
{
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcPubTransparent(_))
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, def.did(), RustcPubTransparent(_)) {
1825 let non_exhaustive = def.is_variant_list_non_exhaustive()
1826 || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1827 if non_exhaustive {
1828 return ControlFlow::Break(NonTrivialReason::NonExhaustive { ty });
1829 }
1830 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1831 if has_priv {
1832 return ControlFlow::Break(NonTrivialReason::PrivateField { inside: ty });
1833 }
1834 }
1835 if def.repr().c() {
1836 return ControlFlow::Break(NonTrivialReason::ReprC { ty });
1837 }
1838 def.all_fields()
1839 .map(|field| field.ty(tcx, args).skip_norm_wip())
1840 .try_for_each(|t| is_trivial(tcx, typing_env, t))
1841 }
1842 _ => ControlFlow::Continue(()),
1843 }
1844 }
1845
1846 let non_trivial_fields = variant
1847 .fields
1848 .iter()
1849 .filter_map(|field| {
1850 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did)).skip_norm_wip();
1851 let layout = tcx.layout_of(typing_env.as_query_input(ty));
1852 let span = tcx.hir_span_if_local(field.did).unwrap();
1854 if !layout.is_ok_and(|layout| layout.is_1zst()) {
1856 let reason = match layout {
1857 Err(_) => NonTrivialReason::UnknownLayout,
1858 Ok(layout) => {
1859 if !(layout.is_sized() && layout.size.bytes() == 0) {
1860 NonTrivialReason::NonZeroSized
1861 } else {
1862 NonTrivialReason::NonTrivialAlignment
1863 }
1864 }
1865 };
1866 return Some(NonTrivialFieldInfo { span, reason });
1867 }
1868 if let Some(reason) = is_trivial(tcx, typing_env, ty).break_value() {
1870 return Some(NonTrivialFieldInfo { span, reason });
1871 }
1872 None
1874 })
1875 .collect::<Vec<_>>();
1876
1877 if non_trivial_fields.len() > 1 {
1878 let count = non_trivial_fields.len();
1879 let desc = if adt.is_enum() {
1880 format_args!("the variant of a transparent {0}", adt.descr())format_args!("the variant of a transparent {}", adt.descr())
1881 } else {
1882 format_args!("transparent {0}", adt.descr())format_args!("transparent {}", adt.descr())
1883 };
1884 let ty_span = tcx.def_span(adt.did());
1885 let mut diag = tcx.dcx().struct_span_err(
1886 ty_span,
1887 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} needs at most one non-trivial field, but has {1}",
desc, count))
})format!("{desc} needs at most one non-trivial field, but has {count}"),
1888 );
1889 diag.code(E0690);
1890
1891 diag.span_label(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("needs at most one non-trivial field, but has {0}",
count))
})format!("needs at most one non-trivial field, but has {count}"));
1893 for field in non_trivial_fields {
1895 let msg = match field.reason {
1896 NonTrivialReason::UnknownLayout => {
1897 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field is generic and hence may have non-zero size"))
})format!("this field is generic and hence may have non-zero size")
1898 }
1899 NonTrivialReason::NonZeroSized => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field has non-zero size"))
})format!("this field has non-zero size"),
1900 NonTrivialReason::NonTrivialAlignment => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field requires alignment"))
})format!("this field requires alignment"),
1901 NonTrivialReason::PrivateField { inside } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field contains `{0}`, which has private fields, so it could become non-zero-sized in the future",
inside))
})format!(
1902 "this field contains `{inside}`, which has private fields, so it could become non-zero-sized in the future"
1903 ),
1904 NonTrivialReason::NonExhaustive { ty } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field contains `{0}`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future",
ty))
})format!(
1905 "this field contains `{ty}`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future"
1906 ),
1907 NonTrivialReason::ReprC { ty } => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field contains `{0}`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets",
ty))
})format!(
1908 "this field contains `{ty}`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets"
1909 ),
1910 };
1911 diag.span_label(field.span, msg);
1912 }
1913
1914 diag.emit();
1915 return;
1916 }
1917}
1918
1919#[allow(trivial_numeric_casts)]
1920fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1921 let def = tcx.adt_def(def_id);
1922 def.destructor(tcx); if def.variants().is_empty() {
1925 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Repr { reprs, first_span
}) => {
break 'done
Some({
{
tcx.dcx().struct_span_err(reprs.first().map(|repr|
repr.1).unwrap_or(*first_span),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsupported representation for zero-variant enum"))
})).with_code(E0084)
}.with_span_label(tcx.def_span(def_id),
"zero-variant enum").emit();
});
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
};find_attr!(tcx, def_id, Repr { reprs, first_span } => {
1926 struct_span_code_err!(
1927 tcx.dcx(),
1928 reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1929 E0084,
1930 "unsupported representation for zero-variant enum"
1931 )
1932 .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1933 .emit();
1934 });
1935 }
1936
1937 for v in def.variants() {
1938 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1939 tcx.ensure_ok().typeck(discr_def_id.expect_local());
1940 }
1941 }
1942
1943 if def.repr().int.is_none() {
1944 let is_unit = |var: &ty::VariantDef| #[allow(non_exhaustive_omitted_patterns)] match var.ctor_kind() {
Some(CtorKind::Const) => true,
_ => false,
}matches!(var.ctor_kind(), Some(CtorKind::Const));
1945 let get_disr = |var: &ty::VariantDef| match var.discr {
1946 ty::VariantDiscr::Explicit(disr) => Some(disr),
1947 ty::VariantDiscr::Relative(_) => None,
1948 };
1949
1950 let non_unit = def.variants().iter().find(|var| !is_unit(var));
1951 let disr_unit =
1952 def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1953 let disr_non_unit =
1954 def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1955
1956 if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1957 let mut err = {
tcx.dcx().struct_span_err(tcx.def_span(def_id),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"))
})).with_code(E0732)
}struct_span_code_err!(
1958 tcx.dcx(),
1959 tcx.def_span(def_id),
1960 E0732,
1961 "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1962 );
1963 if let Some(disr_non_unit) = disr_non_unit {
1964 err.span_label(
1965 tcx.def_span(disr_non_unit),
1966 "explicit discriminant on non-unit variant specified here",
1967 );
1968 } else {
1969 err.span_label(
1970 tcx.def_span(disr_unit.unwrap()),
1971 "explicit discriminant specified here",
1972 );
1973 err.span_label(
1974 tcx.def_span(non_unit.unwrap().def_id),
1975 "non-unit discriminant declared here",
1976 );
1977 }
1978 err.emit();
1979 }
1980 }
1981
1982 detect_discriminant_duplicate(tcx, def);
1983 check_transparent(tcx, def);
1984}
1985
1986fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1988 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1991 let var = adt.variant(idx); let (span, display_discr) = match var.discr {
1993 ty::VariantDiscr::Explicit(discr_def_id) => {
1994 if let hir::Node::AnonConst(expr) =
1996 tcx.hir_node_by_def_id(discr_def_id.expect_local())
1997 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1998 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1999 && *lit_value != dis.val
2000 {
2001 (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` (overflowed from `{1}`)",
dis, lit_value))
})format!("`{dis}` (overflowed from `{lit_value}`)"))
2002 } else {
2003 (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`"))
2005 }
2006 }
2007 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`")),
2009 ty::VariantDiscr::Relative(distance_to_explicit) => {
2010 if let Some(explicit_idx) =
2015 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
2016 {
2017 let explicit_variant = adt.variant(explicit_idx);
2018 let ve_ident = var.name;
2019 let ex_ident = explicit_variant.name;
2020 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
2021
2022 err.span_label(
2023 tcx.def_span(explicit_variant.def_id),
2024 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("discriminant for `{0}` incremented from this startpoint (`{1}` + {2} {3} later => `{0}` = {4})",
ve_ident, ex_ident, distance_to_explicit, sp, dis))
})format!(
2025 "discriminant for `{ve_ident}` incremented from this startpoint \
2026 (`{ex_ident}` + {distance_to_explicit} {sp} later \
2027 => `{ve_ident}` = {dis})"
2028 ),
2029 );
2030 }
2031
2032 (tcx.def_span(var.def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`"))
2033 }
2034 };
2035
2036 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} assigned here", display_discr))
})format!("{display_discr} assigned here"));
2037 };
2038
2039 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
2040
2041 let mut i = 0;
2048 while i < discrs.len() {
2049 let var_i_idx = discrs[i].0;
2050 let mut error: Option<Diag<'_, _>> = None;
2051
2052 let mut o = i + 1;
2053 while o < discrs.len() {
2054 let var_o_idx = discrs[o].0;
2055
2056 if discrs[i].1.val == discrs[o].1.val {
2057 let err = error.get_or_insert_with(|| {
2058 let mut ret = {
tcx.dcx().struct_span_err(tcx.def_span(adt.did()),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("discriminant value `{0}` assigned more than once",
discrs[i].1))
})).with_code(E0081)
}struct_span_code_err!(
2059 tcx.dcx(),
2060 tcx.def_span(adt.did()),
2061 E0081,
2062 "discriminant value `{}` assigned more than once",
2063 discrs[i].1,
2064 );
2065
2066 report(discrs[i].1, var_i_idx, &mut ret);
2067
2068 ret
2069 });
2070
2071 report(discrs[o].1, var_o_idx, err);
2072
2073 discrs[o] = *discrs.last().unwrap();
2075 discrs.pop();
2076 } else {
2077 o += 1;
2078 }
2079 }
2080
2081 if let Some(e) = error {
2082 e.emit();
2083 }
2084
2085 i += 1;
2086 }
2087}
2088
2089fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2090 let generics = tcx.generics_of(def_id);
2091 if generics.own_counts().types == 0 {
2092 return;
2093 }
2094
2095 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
2096 if ty.references_error() {
2097 return;
2099 }
2100
2101 let bounded_params = LazyCell::new(|| {
2103 tcx.explicit_clauses_of(def_id)
2104 .clauses
2105 .iter()
2106 .filter_map(|(clause, span)| {
2107 let bounded_ty = match clause.kind().skip_binder() {
2108 ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
2109 ty::ClauseKind::TypeOutlives(pred) => pred.0,
2110 _ => return None,
2111 };
2112 if let ty::Param(param) = bounded_ty.kind() {
2113 Some((param.index, span))
2114 } else {
2115 None
2116 }
2117 })
2118 .collect::<FxIndexMap<_, _>>()
2124 });
2125
2126 let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
2127 for leaf in ty.walk() {
2128 if let GenericArgKind::Type(leaf_ty) = leaf.kind()
2129 && let ty::Param(param) = leaf_ty.kind()
2130 {
2131 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs:2131",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2131u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
::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!("found use of ty param {0:?}",
param) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("found use of ty param {:?}", param);
2132 params_used.insert(param.index);
2133 }
2134 }
2135
2136 for param in &generics.own_params {
2137 if !params_used.contains(param.index)
2138 && let ty::GenericParamDefKind::Type { .. } = param.kind
2139 {
2140 let span = tcx.def_span(param.def_id);
2141 let param_name = Ident::new(param.name, span);
2142
2143 let has_explicit_bounds = bounded_params.is_empty()
2147 || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span);
2148 let const_param_help = !has_explicit_bounds;
2149
2150 let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2151 span,
2152 param_name,
2153 param_def_kind: tcx.def_descr(param.def_id),
2154 help: diagnostics::UnusedGenericParameterHelp::TyAlias { param_name },
2155 usage_spans: ::alloc::vec::Vec::new()vec![],
2156 const_param_help,
2157 });
2158 diag.code(E0091);
2159 diag.emit();
2160 }
2161 }
2162}
2163
2164fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
2173 let span = tcx.def_span(opaque_def_id);
2174 let mut err = {
tcx.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot resolve opaque type"))
})).with_code(E0720)
}struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
2175
2176 let mut label = false;
2177 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
2178 let typeck_results = tcx.typeck(def_id);
2179 if visitor
2180 .returns
2181 .iter()
2182 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
2183 .all(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Never => true,
_ => false,
}matches!(ty.kind(), ty::Never))
2184 {
2185 let spans = visitor
2186 .returns
2187 .iter()
2188 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
2189 .map(|expr| expr.span)
2190 .collect::<Vec<Span>>();
2191 let span_len = spans.len();
2192 if span_len == 1 {
2193 err.span_label(spans[0], "this returned value is of `!` type");
2194 } else {
2195 let mut multispan: MultiSpan = spans.clone().into();
2196 for span in spans {
2197 multispan.push_span_label(span, "this returned value is of `!` type");
2198 }
2199 err.span_note(multispan, "these returned values have a concrete \"never\" type");
2200 }
2201 err.help("this error will resolve once the item's body returns a concrete type");
2202 } else {
2203 let mut seen = FxHashSet::default();
2204 seen.insert(span);
2205 err.span_label(span, "recursive opaque type");
2206 label = true;
2207 for (sp, ty) in visitor
2208 .returns
2209 .iter()
2210 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
2211 .filter(|(_, ty)| !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Never => true,
_ => false,
}matches!(ty.kind(), ty::Never))
2212 {
2213 #[derive(#[automatically_derived]
impl ::core::default::Default for OpaqueTypeCollector {
#[inline]
fn default() -> OpaqueTypeCollector {
OpaqueTypeCollector {
opaques: ::core::default::Default::default(),
closures: ::core::default::Default::default(),
}
}
}Default)]
2214 struct OpaqueTypeCollector {
2215 opaques: Vec<DefId>,
2216 closures: Vec<DefId>,
2217 }
2218 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
2219 fn visit_ty(&mut self, t: Ty<'tcx>) {
2220 match *t.kind() {
2221 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: def }, .. }) => {
2222 self.opaques.push(def);
2223 }
2224 ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
2225 self.closures.push(def_id);
2226 t.super_visit_with(self);
2227 }
2228 _ => t.super_visit_with(self),
2229 }
2230 }
2231 }
2232
2233 let mut visitor = OpaqueTypeCollector::default();
2234 ty.visit_with(&mut visitor);
2235 for def_id in visitor.opaques {
2236 let ty_span = tcx.def_span(def_id);
2237 if !seen.contains(&ty_span) {
2238 let descr = if ty.is_opaque() { "opaque " } else { "" };
2239 err.span_label(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("returning this {0}type `{1}`",
descr, ty))
})format!("returning this {descr}type `{ty}`"));
2240 seen.insert(ty_span);
2241 }
2242 err.span_label(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("returning here with type `{0}`",
ty))
})format!("returning here with type `{ty}`"));
2243 }
2244
2245 for closure_def_id in visitor.closures {
2246 let Some(closure_local_did) = closure_def_id.as_local() else {
2247 continue;
2248 };
2249 let typeck_results = tcx.typeck(closure_local_did);
2250
2251 let mut label_match = |ty: Ty<'_>, span| {
2252 for arg in ty.walk() {
2253 if let ty::GenericArgKind::Type(ty) = arg.kind()
2254 && let ty::Alias(
2255 _,
2256 ty::AliasTy {
2257 kind: ty::Opaque { def_id: captured_def_id },
2258 ..
2259 },
2260 ) = *ty.kind()
2261 && captured_def_id == opaque_def_id.to_def_id()
2262 {
2263 err.span_label(
2264 span,
2265 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} captures itself here",
tcx.def_descr(closure_def_id)))
})format!(
2266 "{} captures itself here",
2267 tcx.def_descr(closure_def_id)
2268 ),
2269 );
2270 }
2271 }
2272 };
2273
2274 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2276 {
2277 label_match(capture.place.ty(), capture.get_path_span(tcx));
2278 }
2279 if tcx.is_coroutine(closure_def_id)
2281 && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2282 {
2283 for interior_ty in &coroutine_layout.field_tys {
2284 label_match(interior_ty.ty, interior_ty.source_info.span);
2285 }
2286 }
2287 }
2288 }
2289 }
2290 }
2291 if !label {
2292 err.span_label(span, "cannot resolve opaque type");
2293 }
2294 err.emit()
2295}
2296
2297pub(super) fn check_coroutine_obligations(
2298 tcx: TyCtxt<'_>,
2299 def_id: LocalDefId,
2300) -> Result<(), ErrorGuaranteed> {
2301 if true {
if !!tcx.is_typeck_child(def_id.to_def_id()) {
::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def_id.to_def_id())")
};
};debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
2302
2303 let typeck_results = tcx.typeck(def_id);
2304 let param_env = tcx.param_env(def_id);
2305
2306 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs:2306",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2306u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("typeck_results.coroutine_stalled_predicates")
}> =
::tracing::__macro_support::FieldName::new("typeck_results.coroutine_stalled_predicates");
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(&typeck_results.coroutine_stalled_predicates)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?typeck_results.coroutine_stalled_predicates);
2307
2308 let mode = if tcx.next_trait_solver_globally() {
2309 TypingMode::borrowck(tcx, def_id)
2313 } else {
2314 TypingMode::analysis_in_body(tcx, def_id)
2315 };
2316
2317 let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2322
2323 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2324 for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2325 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2326 }
2327
2328 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2329 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs:2329",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2329u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("errors")
}> =
::tracing::__macro_support::FieldName::new("errors");
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(&errors)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?errors);
2330 if let TraitErrors::HasErrors(errors) = errors {
2331 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2332 }
2333
2334 if !tcx.next_trait_solver_globally() {
2335 for (key, ty) in infcx.take_opaque_types() {
2338 let hidden_type = infcx.deeply_resolve_ignoring_regions(ty);
2339 let key = infcx.deeply_resolve_ignoring_regions(key);
2340 sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2341 }
2342 } else {
2343 let _ = infcx.take_opaque_types();
2346 }
2347
2348 Ok(())
2349}
2350
2351pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2352 tcx: TyCtxt<'tcx>,
2353 def_id: LocalDefId,
2354) -> Result<(), ErrorGuaranteed> {
2355 if !tcx.next_trait_solver_globally() {
2356 return Ok(());
2357 }
2358 let typeck_results = tcx.typeck(def_id);
2359 let param_env = tcx.param_env(def_id);
2360
2361 let typing_mode = TypingMode::borrowck(tcx, def_id);
2363 let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2364 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2365 for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2366 let predicate = fold_regions(tcx, *predicate, |_, _| {
2367 infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2368 });
2369 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2370 }
2371
2372 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2373 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs:2373",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2373u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("errors")
}> =
::tracing::__macro_support::FieldName::new("errors");
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(&errors)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?errors);
2374 if let TraitErrors::HasErrors(errors) = errors {
2375 Err(infcx.err_ctxt().report_fulfillment_errors(errors))
2376 } else {
2377 Ok(())
2378 }
2379}