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