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::{DEAD_CODE, UNINHABITED_STATIC, 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_span::sym;
28use rustc_target::spec::{AbiMap, AbiMapping};
29use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
30use rustc_trait_selection::traits;
31use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
32use tracing::{debug, instrument};
33use ty::TypingMode;
34
35use super::compare_impl_item::check_type_bounds;
36use super::*;
37use crate::check::wfcheck::{
38 check_associated_item, check_trait_item, check_type_defn, check_variances_for_type_defn,
39 check_where_clauses, enter_wf_checking_ctxt,
40};
41use crate::collect::ItemCtxt;
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("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/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 wfcheck::check_const_item(wfcx, def_id, ty);
957 Ok(())
958 }));
959
960 return res;
964 }
965 DefKind::TyAlias => {
966 tcx.ensure_ok().generics_of(def_id);
967 tcx.ensure_ok().type_of(def_id);
968 tcx.ensure_ok().clauses_of(def_id);
969 let ty = tcx.type_of(def_id).instantiate_identity();
970 let span = tcx.def_span(def_id);
971 if tcx.type_alias_is_checked(def_id) {
972 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
973 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
974 wfcx.register_wf_obligation(
975 span,
976 Some(WellFormedLoc::Ty(def_id)),
977 item_ty.into(),
978 );
979 check_where_clauses(wfcx, def_id);
980 Ok(())
981 }));
982 } else {
983 check_type_alias_type_params_are_used(tcx, def_id);
984 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
985 if let Some(unnormalized_obligations) = wfcx.unnormalized_obligations(span, ty.skip_norm_wip())
996 {
997 let filtered_obligations =
998 unnormalized_obligations.into_iter().filter(|o| {
999 #[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(),
1000 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
1001 if matches!(ct.kind(), ty::ConstKind::Param(..)))
1002 });
1003 wfcx.ocx.register_obligations(filtered_obligations)
1004 }
1005 Ok(())
1006 }));
1007 }
1008
1009 return res;
1013 }
1014 DefKind::ForeignMod => {
1015 let it = tcx.hir_expect_item(def_id);
1016 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
1017 return Ok(());
1018 };
1019
1020 check_abi(tcx, it.hir_id(), it.span, abi);
1021
1022 for &item in items {
1023 let def_id = item.owner_id.def_id;
1024
1025 let generics = tcx.generics_of(def_id);
1026 let own_counts = generics.own_counts();
1027 if generics.own_params.len() - own_counts.lifetimes != 0 {
1028 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
1029 (_, 0) => ("type", "types", Some("u32")),
1030 (0, _) => ("const", "consts", None),
1033 _ => ("type or const", "types or consts", None),
1034 };
1035 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) {
1036 "externally implementable items"
1037 } else {
1038 "foreign items"
1039 };
1040
1041 let span = tcx.def_span(def_id);
1042 {
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!(
1043 tcx.dcx(),
1044 span,
1045 E0044,
1046 "{name} may not have {kinds} parameters",
1047 )
1048 .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"))
1049 .with_help(
1050 ::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!(
1053 "replace the {} parameters with concrete {}{}",
1054 kinds,
1055 kinds_pl,
1056 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
1057 ),
1058 )
1059 .emit();
1060 }
1061
1062 tcx.ensure_ok().generics_of(def_id);
1063 tcx.ensure_ok().type_of(def_id);
1064 tcx.ensure_ok().clauses_of(def_id);
1065 if tcx.is_conditionally_const(def_id) {
1066 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1067 tcx.ensure_ok().const_conditions(def_id);
1068 }
1069 match tcx.def_kind(def_id) {
1070 DefKind::Fn => {
1071 tcx.ensure_ok().codegen_fn_attrs(def_id);
1072 tcx.ensure_ok().fn_sig(def_id);
1073 let item = tcx.hir_foreign_item(item);
1074 let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1075 check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1076 }
1077 DefKind::Static { .. } => {
1078 tcx.ensure_ok().codegen_fn_attrs(def_id);
1079 }
1080 _ => (),
1081 }
1082 }
1083 return res;
1085 }
1086 DefKind::Closure => {
1087 tcx.ensure_ok().codegen_fn_attrs(def_id);
1091 return res;
1099 }
1100 DefKind::AssocFn => {
1101 tcx.ensure_ok().codegen_fn_attrs(def_id);
1102 tcx.ensure_ok().type_of(def_id);
1103 tcx.ensure_ok().fn_sig(def_id);
1104 tcx.ensure_ok().clauses_of(def_id);
1105 res = res.and(check_associated_item(tcx, def_id));
1106 let assoc_item = tcx.associated_item(def_id);
1107 match assoc_item.container {
1108 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1109 ty::AssocContainer::Trait => {
1110 res = res.and(check_trait_item(tcx, def_id));
1111 }
1112 }
1113
1114 return res;
1118 }
1119 DefKind::AssocConst { .. } => {
1120 tcx.ensure_ok().type_of(def_id);
1121 tcx.ensure_ok().clauses_of(def_id);
1122 res = res.and(check_associated_item(tcx, def_id));
1123 let assoc_item = tcx.associated_item(def_id);
1124 match assoc_item.container {
1125 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1126 ty::AssocContainer::Trait => {
1127 res = res.and(check_trait_item(tcx, def_id));
1128 }
1129 }
1130
1131 return res;
1135 }
1136 DefKind::AssocTy => {
1137 tcx.ensure_ok().clauses_of(def_id);
1138 res = res.and(check_associated_item(tcx, def_id));
1139
1140 let assoc_item = tcx.associated_item(def_id);
1141 let has_type = match assoc_item.container {
1142 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1143 ty::AssocContainer::Trait => {
1144 tcx.ensure_ok().explicit_item_bounds(def_id);
1145 tcx.ensure_ok().explicit_item_self_bounds(def_id);
1146 if tcx.is_conditionally_const(def_id) {
1147 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1148 tcx.ensure_ok().const_conditions(def_id);
1149 }
1150 res = res.and(check_trait_item(tcx, def_id));
1151 assoc_item.defaultness(tcx).has_value()
1152 }
1153 };
1154 if has_type {
1155 tcx.ensure_ok().type_of(def_id);
1156 }
1157
1158 return res;
1162 }
1163 DefKind::TestBinderConstraints => {
1164 tcx.ensure_ok().generics_of(def_id);
1165 tcx.ensure_ok().clauses_of(def_id);
1166 let (_, body) =
1167 tcx.hir_node_by_def_id(def_id).expect_item().expect_test_binder_constraints();
1168 let icx = ItemCtxt::new(tcx, def_id);
1169 let lowered = icx.lower_test_binder_body(body);
1170 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1171 wfcx.check_test_binder_body(lowered);
1172 Ok(())
1173 }));
1174 return res;
1175 }
1176
1177 DefKind::AnonConst
1179 | DefKind::ExternCrate
1180 | DefKind::Macro(..)
1181 | DefKind::Use
1182 | DefKind::GlobalAsm
1183 | DefKind::Mod => return res,
1184
1185 DefKind::ForeignTy => {}
1186
1187 DefKind::Variant
1188 | DefKind::TyParam
1189 | DefKind::ConstParam
1190 | DefKind::Ctor(..)
1191 | DefKind::Field
1192 | DefKind::LifetimeParam
1193 | DefKind::SyntheticCoroutineBody => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{1:?}: {0:?}", tcx.def_kind(def_id), def_id)));
}unreachable!("{def_id:?}: {:?}", tcx.def_kind(def_id)),
1194 }
1195 let node = tcx.hir_node_by_def_id(def_id);
1196 res.and(match node {
1197 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"),
1198 hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1199 hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1200 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", node)));
}unreachable!("{node:?}"),
1201 })
1202}
1203
1204pub(super) fn check_specialization_validity<'tcx>(
1205 tcx: TyCtxt<'tcx>,
1206 trait_def: &ty::TraitDef,
1207 trait_item: ty::AssocItem,
1208 impl_id: DefId,
1209 impl_item: DefId,
1210) {
1211 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1212 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1213 if parent.is_from_trait() {
1214 None
1215 } else {
1216 Some((parent, parent.item(tcx, trait_item.def_id)))
1217 }
1218 });
1219
1220 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1221 match parent_item {
1222 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1225 Some(Err(parent_impl.def_id()))
1226 }
1227
1228 Some(_) => Some(Ok(())),
1230
1231 None => {
1235 if tcx.defaultness(parent_impl.def_id()).is_default() {
1236 None
1237 } else {
1238 Some(Err(parent_impl.def_id()))
1239 }
1240 }
1241 }
1242 });
1243
1244 let result = opt_result.unwrap_or(Ok(()));
1247
1248 if let Err(parent_impl) = result {
1249 if !tcx.is_impl_trait_in_trait(impl_item) {
1250 let span = tcx.def_span(impl_item);
1251 let ident = tcx.item_ident(impl_item);
1252
1253 let err = match tcx.span_of_impl(parent_impl) {
1254 Ok(sp) => diagnostics::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp },
1255 Err(cname) => diagnostics::ImplNotMarkedDefault::Err { span, ident, cname },
1256 };
1257
1258 tcx.dcx().emit_err(err);
1259 } else {
1260 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"));
1261 }
1262 }
1263}
1264
1265fn check_overriding_final_trait_item<'tcx>(
1266 tcx: TyCtxt<'tcx>,
1267 trait_item: ty::AssocItem,
1268 impl_item: ty::AssocItem,
1269) {
1270 if trait_item.is_fn() && trait_item.defaultness(tcx).is_final() {
1271 tcx.dcx().emit_err(diagnostics::OverridingFinalTraitFunction {
1272 impl_span: tcx.def_span(impl_item.def_id),
1273 trait_span: tcx.def_span(trait_item.def_id),
1274 ident: tcx.item_ident(impl_item.def_id),
1275 });
1276 }
1277}
1278
1279fn check_impl_items_against_trait<'tcx>(
1280 tcx: TyCtxt<'tcx>,
1281 impl_id: LocalDefId,
1282 impl_trait_header: ty::ImplTraitHeader<'tcx>,
1283) {
1284 let trait_ref = impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip();
1285 if trait_ref.references_error() {
1289 return;
1290 }
1291
1292 let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1293
1294 match impl_trait_header.polarity {
1296 ty::ImplPolarity::Positive => {}
1297 ty::ImplPolarity::Negative => {
1298 if let [first_item_ref, ..] = *impl_item_refs {
1299 let first_item_span = tcx.def_span(first_item_ref);
1300 {
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!(
1301 tcx.dcx(),
1302 first_item_span,
1303 E0749,
1304 "negative impls cannot have any items"
1305 )
1306 .emit();
1307 }
1308 return;
1309 }
1310 }
1311
1312 let trait_def = tcx.trait_def(trait_ref.def_id);
1313
1314 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1315
1316 for &impl_item in impl_item_refs {
1317 let ty_impl_item = tcx.associated_item(impl_item);
1318 let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1319 Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1320 Err(ErrorGuaranteed { .. }) => continue,
1321 };
1322
1323 let res = tcx.ensure_result().compare_impl_item(impl_item.expect_local());
1324 if res.is_ok() {
1325 match ty_impl_item.kind {
1326 ty::AssocKind::Fn { .. } => {
1327 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1328 tcx,
1329 ty_impl_item,
1330 ty_trait_item,
1331 tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1332 .instantiate_identity()
1333 .skip_norm_wip(),
1334 );
1335 }
1336 ty::AssocKind::Const { .. } => {}
1337 ty::AssocKind::Type { .. } => {}
1338 }
1339 }
1340
1341 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1342 tcx.emit_node_span_lint(
1343 DEAD_CODE,
1344 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1345 tcx.def_span(ty_impl_item.def_id),
1346 diagnostics::UselessImplItem,
1347 )
1348 }
1349
1350 check_specialization_validity(
1351 tcx,
1352 trait_def,
1353 ty_trait_item,
1354 impl_id.to_def_id(),
1355 impl_item,
1356 );
1357
1358 check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item);
1359 }
1360
1361 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1362 let mut missing_items = Vec::new();
1364
1365 let mut must_implement_one_of: Option<&[Ident]> =
1366 trait_def.must_implement_one_of.as_deref();
1367
1368 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1369 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1370
1371 let is_implemented = leaf_def
1372 .as_ref()
1373 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1374
1375 if !is_implemented
1376 && tcx.defaultness(impl_id).is_final()
1377 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1379 {
1380 missing_items.push(tcx.associated_item(trait_item_id));
1381 }
1382
1383 let is_implemented_here =
1385 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1386
1387 if !is_implemented_here {
1388 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1389 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1390 EvalResult::Deny { .. }
1393 if !tcx.features().pin_ergonomics()
1394 && tcx.is_lang_item(trait_ref.def_id, LangItem::Drop)
1395 && tcx.item_name(trait_item_id) == sym::drop =>
1396 {
1397 missing_items.push(tcx.associated_item(trait_item_id));
1398 }
1399 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1400 tcx,
1401 full_impl_span,
1402 trait_item_id,
1403 feature,
1404 reason,
1405 issue,
1406 ),
1407
1408 EvalResult::Allow | EvalResult::Unmarked => {}
1410 }
1411 }
1412
1413 if let Some(required_items) = &must_implement_one_of {
1414 if is_implemented_here {
1415 let trait_item = tcx.associated_item(trait_item_id);
1416 if required_items.contains(&trait_item.ident(tcx)) {
1417 must_implement_one_of = None;
1418 }
1419 }
1420 }
1421
1422 if let Some(leaf_def) = &leaf_def
1423 && !leaf_def.is_final()
1424 && let def_id = leaf_def.item.def_id
1425 && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1426 {
1427 let def_kind = tcx.def_kind(def_id);
1428 let descr = tcx.def_kind_descr(def_kind, def_id);
1429 let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1430 (
1431 ::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"),
1432 "async functions in traits",
1433 )
1434 } else {
1435 (
1436 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} with return-position `impl Trait` in trait cannot be specialized",
descr))
})format!(
1437 "{descr} with return-position `impl Trait` in trait cannot be specialized"
1438 ),
1439 "return position `impl Trait` in traits",
1440 )
1441 };
1442 tcx.dcx()
1443 .struct_span_err(tcx.def_span(def_id), msg)
1444 .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!(
1445 "specialization behaves in inconsistent and surprising ways with \
1446 {feature}, and for now is disallowed"
1447 ))
1448 .emit();
1449 }
1450 }
1451
1452 if !missing_items.is_empty() {
1453 missing_items_err(tcx, impl_id, &missing_items);
1454 }
1455
1456 if let Some(missing_items) = must_implement_one_of {
1457 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);
1458 let missing_items = missing_items.into_iter().map(|i| i.name);
1459 missing_items_must_implement_one_of_err(tcx, impl_id, missing_items, attr_span);
1460 }
1461 }
1462}
1463
1464fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1465 let t = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1466 if let ty::Adt(def, args) = t.kind()
1467 && def.is_struct()
1468 {
1469 let fields = &def.non_enum_variant().fields;
1470 if fields.is_empty() {
1471 {
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();
1472 return;
1473 }
1474
1475 let array_field = &fields[FieldIdx::ZERO];
1476 let array_ty = array_field.ty(tcx, args).skip_norm_wip();
1477 let ty::Array(element_ty, len_const) = array_ty.kind() else {
1478 {
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!(
1479 tcx.dcx(),
1480 sp,
1481 E0076,
1482 "SIMD vector's only field must be an array"
1483 )
1484 .with_span_label(tcx.def_span(array_field.did), "not an array")
1485 .emit();
1486 return;
1487 };
1488
1489 if let Some(second_field) = fields.get(FieldIdx::ONE) {
1490 {
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")
1491 .with_span_label(tcx.def_span(second_field.did), "excess field")
1492 .emit();
1493 return;
1494 }
1495
1496 if let Some(len) = len_const.try_to_target_usize(tcx) {
1501 if len == 0 {
1502 {
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();
1503 return;
1504 } else if len > MAX_SIMD_LANES.into() {
1505 {
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!(
1506 tcx.dcx(),
1507 sp,
1508 E0075,
1509 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1510 )
1511 .emit();
1512 return;
1513 }
1514 }
1515
1516 match element_ty.kind() {
1521 ty::Param(_) => (), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), _ => {
1524 {
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!(
1525 tcx.dcx(),
1526 sp,
1527 E0077,
1528 "SIMD vector element type should be a \
1529 primitive scalar (integer/float/pointer) type"
1530 )
1531 .emit();
1532 return;
1533 }
1534 }
1535 }
1536}
1537
1538{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_scalable_vector",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(1538u32),
::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")]
1539fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {
1540 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1541 let ty::Adt(def, args) = ty.kind() else { return };
1542 if !def.is_struct() {
1543 tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
1544 return;
1545 }
1546
1547 let fields = &def.non_enum_variant().fields;
1548 match scalable {
1549 ScalableElt::ElementCount(..) if fields.is_empty() => {
1550 let mut err =
1551 tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1552 err.help("scalable vector types' only field must be a primitive scalar type");
1553 err.emit();
1554 return;
1555 }
1556 ScalableElt::ElementCount(..) if fields.len() >= 2 => {
1557 tcx.dcx().struct_span_err(span, "scalable vectors cannot have multiple fields").emit();
1558 return;
1559 }
1560 ScalableElt::Container if fields.is_empty() => {
1561 let mut err = tcx
1562 .dcx()
1563 .struct_span_err(span, "scalable vector tuples must have at least one field");
1564 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1565 err.emit();
1566 return;
1567 }
1568 ScalableElt::Container if fields.len() > 8 => {
1569 let mut err = tcx
1570 .dcx()
1571 .struct_span_err(span, "scalable vector tuples can have at most eight fields");
1572 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1573 err.emit();
1574 return;
1575 }
1576 _ => {}
1577 }
1578
1579 match scalable {
1580 ScalableElt::ElementCount(..) => {
1581 let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args).skip_norm_wip();
1582
1583 match element_ty.kind() {
1587 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
1588 _ => {
1589 let mut err = tcx.dcx().struct_span_err(
1590 span,
1591 "element type of a scalable vector must be a primitive scalar",
1592 );
1593 err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
1594 err.emit();
1595 }
1596 }
1597 }
1598 ScalableElt::Container => {
1599 let mut prev_field_ty = None;
1600 for field in fields.iter() {
1601 let element_ty = field.ty(tcx, args).skip_norm_wip();
1602 if let ty::Adt(def, _) = element_ty.kind()
1603 && def.repr().scalable()
1604 {
1605 match def
1606 .repr()
1607 .scalable
1608 .expect("`repr().scalable.is_some()` != `repr().scalable()`")
1609 {
1610 ScalableElt::ElementCount(_) => { }
1611 ScalableElt::Container => {
1612 tcx.dcx().span_err(
1613 tcx.def_span(field.did),
1614 "scalable vector structs cannot contain other scalable vector structs",
1615 );
1616 break;
1617 }
1618 }
1619 } else {
1620 tcx.dcx().span_err(
1621 tcx.def_span(field.did),
1622 "scalable vector structs can only have scalable vector fields",
1623 );
1624 break;
1625 }
1626
1627 if let Some(prev_ty) = prev_field_ty.replace(element_ty)
1628 && prev_ty != element_ty
1629 {
1630 tcx.dcx().span_err(
1631 tcx.def_span(field.did),
1632 "all fields in a scalable vector struct must be the same type",
1633 );
1634 break;
1635 }
1636 }
1637 }
1638 }
1639}
1640
1641pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1642 let repr = def.repr();
1643 if repr.packed() {
1644 if def.is_pin_project() {
1648 tcx.dcx().emit_err(diagnostics::PinV2OnPacked {
1649 span: sp,
1650 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),
1651 adt_name: tcx.item_name(def.did()),
1652 });
1653 }
1654 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) {
1655 for (r, _) in reprs {
1656 if let ReprPacked(pack) = r
1657 && let Some(repr_pack) = repr.pack
1658 && pack != &repr_pack
1659 {
1660 {
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!(
1661 tcx.dcx(),
1662 sp,
1663 E0634,
1664 "type has conflicting packed representation hints"
1665 )
1666 .emit();
1667 }
1668 }
1669 }
1670 if repr.align.is_some() {
1671 {
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!(
1672 tcx.dcx(),
1673 sp,
1674 E0587,
1675 "type has conflicting packed and align representation hints"
1676 )
1677 .emit();
1678 } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut ::alloc::vec::Vec::new()vec![]) {
1679 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!(
1680 tcx.dcx(),
1681 sp,
1682 E0588,
1683 "packed type cannot transitively contain a `#[repr(align)]` type"
1684 );
1685
1686 err.span_note(
1687 tcx.def_span(def_spans[0].0),
1688 ::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)),
1689 );
1690
1691 if def_spans.len() > 2 {
1692 let mut first = true;
1693 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1694 let ident = tcx.item_name(*adt_def);
1695 err.span_note(
1696 *span,
1697 if first {
1698 ::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!(
1699 "`{}` contains a field of type `{}`",
1700 tcx.type_of(def.did()).instantiate_identity().skip_norm_wip(),
1701 ident
1702 )
1703 } else {
1704 ::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}`")
1705 },
1706 );
1707 first = false;
1708 }
1709 }
1710
1711 err.emit();
1712 }
1713 }
1714}
1715
1716pub(super) fn check_packed_inner(
1717 tcx: TyCtxt<'_>,
1718 def_id: DefId,
1719 stack: &mut Vec<DefId>,
1720) -> Option<Vec<(DefId, Span)>> {
1721 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
1722 if def.is_struct() || def.is_union() {
1723 if def.repr().align.is_some() {
1724 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)]);
1725 }
1726
1727 stack.push(def_id);
1728 for field in &def.non_enum_variant().fields {
1729 if let ty::Adt(def, _) = field.ty(tcx, args).skip_norm_wip().kind()
1730 && !stack.contains(&def.did())
1731 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1732 {
1733 defs.push((def.did(), field.ident(tcx).span));
1734 return Some(defs);
1735 }
1736 }
1737 stack.pop();
1738 }
1739 }
1740
1741 None
1742}
1743
1744pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1745 if !adt.repr().transparent() {
1746 return;
1747 }
1748
1749 if adt.is_union() && !tcx.features().transparent_unions() {
1750 feature_err(
1751 &tcx.sess,
1752 sym::transparent_unions,
1753 tcx.def_span(adt.did()),
1754 "transparent unions are unstable",
1755 )
1756 .emit();
1757 }
1758
1759 if adt.variants().len() != 1 {
1760 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1761 return;
1763 }
1764 let variant = adt.variant(VariantIdx::ZERO);
1765
1766 if variant.fields.len() <= 1 {
1767 return;
1769 }
1770
1771 let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1772
1773 enum NonTrivialReason<'tcx> {
1777 UnknownLayout,
1778 NonZeroSized,
1779 NonTrivialAlignment,
1780 PrivateField { inside: Ty<'tcx> },
1781 NonExhaustive { ty: Ty<'tcx> },
1782 ReprC { ty: Ty<'tcx> },
1783 }
1784 struct NonTrivialFieldInfo<'tcx> {
1785 span: Span,
1786 reason: NonTrivialReason<'tcx>,
1787 }
1788
1789 fn is_trivial<'tcx>(
1792 tcx: TyCtxt<'tcx>,
1793 typing_env: ty::TypingEnv<'tcx>,
1794 ty: Ty<'tcx>,
1795 ) -> ControlFlow<NonTrivialReason<'tcx>> {
1796 let ty =
1798 tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
1799 match ty.kind() {
1800 ty::Tuple(list) => list.iter().try_for_each(|t| is_trivial(tcx, typing_env, t)),
1801 ty::Array(ty, _) => is_trivial(tcx, typing_env, *ty),
1802 ty::Adt(def, args) => {
1803 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(_)) {
1804 let non_exhaustive = def.is_variant_list_non_exhaustive()
1805 || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1806 if non_exhaustive {
1807 return ControlFlow::Break(NonTrivialReason::NonExhaustive { ty });
1808 }
1809 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1810 if has_priv {
1811 return ControlFlow::Break(NonTrivialReason::PrivateField { inside: ty });
1812 }
1813 }
1814 if def.repr().c() {
1815 return ControlFlow::Break(NonTrivialReason::ReprC { ty });
1816 }
1817 def.all_fields()
1818 .map(|field| field.ty(tcx, args).skip_norm_wip())
1819 .try_for_each(|t| is_trivial(tcx, typing_env, t))
1820 }
1821 _ => ControlFlow::Continue(()),
1822 }
1823 }
1824
1825 let non_trivial_fields = variant
1826 .fields
1827 .iter()
1828 .filter_map(|field| {
1829 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did)).skip_norm_wip();
1830 let layout = tcx.layout_of(typing_env.as_query_input(ty));
1831 let span = tcx.hir_span_if_local(field.did).unwrap();
1833 if !layout.is_ok_and(|layout| layout.is_1zst()) {
1835 let reason = match layout {
1836 Err(_) => NonTrivialReason::UnknownLayout,
1837 Ok(layout) => {
1838 if !(layout.is_sized() && layout.size.bytes() == 0) {
1839 NonTrivialReason::NonZeroSized
1840 } else {
1841 NonTrivialReason::NonTrivialAlignment
1842 }
1843 }
1844 };
1845 return Some(NonTrivialFieldInfo { span, reason });
1846 }
1847 if let Some(reason) = is_trivial(tcx, typing_env, ty).break_value() {
1849 return Some(NonTrivialFieldInfo { span, reason });
1850 }
1851 None
1853 })
1854 .collect::<Vec<_>>();
1855
1856 if non_trivial_fields.len() > 1 {
1857 let count = non_trivial_fields.len();
1858 let desc = if adt.is_enum() {
1859 format_args!("the variant of a transparent {0}", adt.descr())format_args!("the variant of a transparent {}", adt.descr())
1860 } else {
1861 format_args!("transparent {0}", adt.descr())format_args!("transparent {}", adt.descr())
1862 };
1863 let ty_span = tcx.def_span(adt.did());
1864 let mut diag = tcx.dcx().struct_span_err(
1865 ty_span,
1866 ::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}"),
1867 );
1868 diag.code(E0690);
1869
1870 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}"));
1872 for field in non_trivial_fields {
1874 let msg = match field.reason {
1875 NonTrivialReason::UnknownLayout => {
1876 ::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")
1877 }
1878 NonTrivialReason::NonZeroSized => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field has non-zero size"))
})format!("this field has non-zero size"),
1879 NonTrivialReason::NonTrivialAlignment => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field requires alignment"))
})format!("this field requires alignment"),
1880 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!(
1881 "this field contains `{inside}`, which has private fields, so it could become non-zero-sized in the future"
1882 ),
1883 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!(
1884 "this field contains `{ty}`, which is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future"
1885 ),
1886 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!(
1887 "this field contains `{ty}`, which is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets"
1888 ),
1889 };
1890 diag.span_label(field.span, msg);
1891 }
1892
1893 diag.emit();
1894 return;
1895 }
1896}
1897
1898#[allow(trivial_numeric_casts)]
1899fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1900 let def = tcx.adt_def(def_id);
1901 def.destructor(tcx); if def.variants().is_empty() {
1904 {
{
'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 } => {
1905 struct_span_code_err!(
1906 tcx.dcx(),
1907 reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1908 E0084,
1909 "unsupported representation for zero-variant enum"
1910 )
1911 .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1912 .emit();
1913 });
1914 }
1915
1916 for v in def.variants() {
1917 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1918 tcx.ensure_ok().typeck(discr_def_id.expect_local());
1919 }
1920 }
1921
1922 if def.repr().int.is_none() {
1923 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));
1924 let get_disr = |var: &ty::VariantDef| match var.discr {
1925 ty::VariantDiscr::Explicit(disr) => Some(disr),
1926 ty::VariantDiscr::Relative(_) => None,
1927 };
1928
1929 let non_unit = def.variants().iter().find(|var| !is_unit(var));
1930 let disr_unit =
1931 def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1932 let disr_non_unit =
1933 def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1934
1935 if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1936 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!(
1937 tcx.dcx(),
1938 tcx.def_span(def_id),
1939 E0732,
1940 "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1941 );
1942 if let Some(disr_non_unit) = disr_non_unit {
1943 err.span_label(
1944 tcx.def_span(disr_non_unit),
1945 "explicit discriminant on non-unit variant specified here",
1946 );
1947 } else {
1948 err.span_label(
1949 tcx.def_span(disr_unit.unwrap()),
1950 "explicit discriminant specified here",
1951 );
1952 err.span_label(
1953 tcx.def_span(non_unit.unwrap().def_id),
1954 "non-unit discriminant declared here",
1955 );
1956 }
1957 err.emit();
1958 }
1959 }
1960
1961 detect_discriminant_duplicate(tcx, def);
1962 check_transparent(tcx, def);
1963}
1964
1965fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1967 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1970 let var = adt.variant(idx); let (span, display_discr) = match var.discr {
1972 ty::VariantDiscr::Explicit(discr_def_id) => {
1973 if let hir::Node::AnonConst(expr) =
1975 tcx.hir_node_by_def_id(discr_def_id.expect_local())
1976 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1977 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1978 && *lit_value != dis.val
1979 {
1980 (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}`)"))
1981 } else {
1982 (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`"))
1984 }
1985 }
1986 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`")),
1988 ty::VariantDiscr::Relative(distance_to_explicit) => {
1989 if let Some(explicit_idx) =
1994 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1995 {
1996 let explicit_variant = adt.variant(explicit_idx);
1997 let ve_ident = var.name;
1998 let ex_ident = explicit_variant.name;
1999 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
2000
2001 err.span_label(
2002 tcx.def_span(explicit_variant.def_id),
2003 ::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!(
2004 "discriminant for `{ve_ident}` incremented from this startpoint \
2005 (`{ex_ident}` + {distance_to_explicit} {sp} later \
2006 => `{ve_ident}` = {dis})"
2007 ),
2008 );
2009 }
2010
2011 (tcx.def_span(var.def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`"))
2012 }
2013 };
2014
2015 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} assigned here", display_discr))
})format!("{display_discr} assigned here"));
2016 };
2017
2018 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
2019
2020 let mut i = 0;
2027 while i < discrs.len() {
2028 let var_i_idx = discrs[i].0;
2029 let mut error: Option<Diag<'_, _>> = None;
2030
2031 let mut o = i + 1;
2032 while o < discrs.len() {
2033 let var_o_idx = discrs[o].0;
2034
2035 if discrs[i].1.val == discrs[o].1.val {
2036 let err = error.get_or_insert_with(|| {
2037 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!(
2038 tcx.dcx(),
2039 tcx.def_span(adt.did()),
2040 E0081,
2041 "discriminant value `{}` assigned more than once",
2042 discrs[i].1,
2043 );
2044
2045 report(discrs[i].1, var_i_idx, &mut ret);
2046
2047 ret
2048 });
2049
2050 report(discrs[o].1, var_o_idx, err);
2051
2052 discrs[o] = *discrs.last().unwrap();
2054 discrs.pop();
2055 } else {
2056 o += 1;
2057 }
2058 }
2059
2060 if let Some(e) = error {
2061 e.emit();
2062 }
2063
2064 i += 1;
2065 }
2066}
2067
2068fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2069 let generics = tcx.generics_of(def_id);
2070 if generics.own_counts().types == 0 {
2071 return;
2072 }
2073
2074 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
2075 if ty.references_error() {
2076 return;
2078 }
2079
2080 let bounded_params = LazyCell::new(|| {
2082 tcx.explicit_clauses_of(def_id)
2083 .clauses
2084 .iter()
2085 .filter_map(|(clause, span)| {
2086 let bounded_ty = match clause.kind().skip_binder() {
2087 ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
2088 ty::ClauseKind::TypeOutlives(pred) => pred.0,
2089 _ => return None,
2090 };
2091 if let ty::Param(param) = bounded_ty.kind() {
2092 Some((param.index, span))
2093 } else {
2094 None
2095 }
2096 })
2097 .collect::<FxIndexMap<_, _>>()
2103 });
2104
2105 let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
2106 for leaf in ty.walk() {
2107 if let GenericArgKind::Type(leaf_ty) = leaf.kind()
2108 && let ty::Param(param) = leaf_ty.kind()
2109 {
2110 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs:2110",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2110u32),
::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);
2111 params_used.insert(param.index);
2112 }
2113 }
2114
2115 for param in &generics.own_params {
2116 if !params_used.contains(param.index)
2117 && let ty::GenericParamDefKind::Type { .. } = param.kind
2118 {
2119 let span = tcx.def_span(param.def_id);
2120 let param_name = Ident::new(param.name, span);
2121
2122 let has_explicit_bounds = bounded_params.is_empty()
2126 || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span);
2127 let const_param_help = !has_explicit_bounds;
2128
2129 let mut diag = tcx.dcx().create_err(diagnostics::UnusedGenericParameter {
2130 span,
2131 param_name,
2132 param_def_kind: tcx.def_descr(param.def_id),
2133 help: diagnostics::UnusedGenericParameterHelp::TyAlias { param_name },
2134 usage_spans: ::alloc::vec::Vec::new()vec![],
2135 const_param_help,
2136 });
2137 diag.code(E0091);
2138 diag.emit();
2139 }
2140 }
2141}
2142
2143fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
2152 let span = tcx.def_span(opaque_def_id);
2153 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");
2154
2155 let mut label = false;
2156 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
2157 let typeck_results = tcx.typeck(def_id);
2158 if visitor
2159 .returns
2160 .iter()
2161 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
2162 .all(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Never => true,
_ => false,
}matches!(ty.kind(), ty::Never))
2163 {
2164 let spans = visitor
2165 .returns
2166 .iter()
2167 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
2168 .map(|expr| expr.span)
2169 .collect::<Vec<Span>>();
2170 let span_len = spans.len();
2171 if span_len == 1 {
2172 err.span_label(spans[0], "this returned value is of `!` type");
2173 } else {
2174 let mut multispan: MultiSpan = spans.clone().into();
2175 for span in spans {
2176 multispan.push_span_label(span, "this returned value is of `!` type");
2177 }
2178 err.span_note(multispan, "these returned values have a concrete \"never\" type");
2179 }
2180 err.help("this error will resolve once the item's body returns a concrete type");
2181 } else {
2182 let mut seen = FxHashSet::default();
2183 seen.insert(span);
2184 err.span_label(span, "recursive opaque type");
2185 label = true;
2186 for (sp, ty) in visitor
2187 .returns
2188 .iter()
2189 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
2190 .filter(|(_, ty)| !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Never => true,
_ => false,
}matches!(ty.kind(), ty::Never))
2191 {
2192 #[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)]
2193 struct OpaqueTypeCollector {
2194 opaques: Vec<DefId>,
2195 closures: Vec<DefId>,
2196 }
2197 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
2198 fn visit_ty(&mut self, t: Ty<'tcx>) {
2199 match *t.kind() {
2200 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: def }, .. }) => {
2201 self.opaques.push(def);
2202 }
2203 ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
2204 self.closures.push(def_id);
2205 t.super_visit_with(self);
2206 }
2207 _ => t.super_visit_with(self),
2208 }
2209 }
2210 }
2211
2212 let mut visitor = OpaqueTypeCollector::default();
2213 ty.visit_with(&mut visitor);
2214 for def_id in visitor.opaques {
2215 let ty_span = tcx.def_span(def_id);
2216 if !seen.contains(&ty_span) {
2217 let descr = if ty.is_opaque() { "opaque " } else { "" };
2218 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}`"));
2219 seen.insert(ty_span);
2220 }
2221 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}`"));
2222 }
2223
2224 for closure_def_id in visitor.closures {
2225 let Some(closure_local_did) = closure_def_id.as_local() else {
2226 continue;
2227 };
2228 let typeck_results = tcx.typeck(closure_local_did);
2229
2230 let mut label_match = |ty: Ty<'_>, span| {
2231 for arg in ty.walk() {
2232 if let ty::GenericArgKind::Type(ty) = arg.kind()
2233 && let ty::Alias(
2234 _,
2235 ty::AliasTy {
2236 kind: ty::Opaque { def_id: captured_def_id },
2237 ..
2238 },
2239 ) = *ty.kind()
2240 && captured_def_id == opaque_def_id.to_def_id()
2241 {
2242 err.span_label(
2243 span,
2244 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} captures itself here",
tcx.def_descr(closure_def_id)))
})format!(
2245 "{} captures itself here",
2246 tcx.def_descr(closure_def_id)
2247 ),
2248 );
2249 }
2250 }
2251 };
2252
2253 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2255 {
2256 label_match(capture.place.ty(), capture.get_path_span(tcx));
2257 }
2258 if tcx.is_coroutine(closure_def_id)
2260 && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2261 {
2262 for interior_ty in &coroutine_layout.field_tys {
2263 label_match(interior_ty.ty, interior_ty.source_info.span);
2264 }
2265 }
2266 }
2267 }
2268 }
2269 }
2270 if !label {
2271 err.span_label(span, "cannot resolve opaque type");
2272 }
2273 err.emit()
2274}
2275
2276pub(super) fn check_coroutine_obligations(
2277 tcx: TyCtxt<'_>,
2278 def_id: LocalDefId,
2279) -> Result<(), ErrorGuaranteed> {
2280 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()));
2281
2282 let typeck_results = tcx.typeck(def_id);
2283 let param_env = tcx.param_env(def_id);
2284
2285 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs:2285",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2285u32),
::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);
2286
2287 let mode = if tcx.next_trait_solver_globally() {
2288 TypingMode::borrowck(tcx, def_id)
2292 } else {
2293 TypingMode::analysis_in_body(tcx, def_id)
2294 };
2295
2296 let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2301
2302 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2303 for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2304 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2305 }
2306
2307 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2308 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs:2308",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2308u32),
::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);
2309 if let TraitErrors::HasErrors(errors) = errors {
2310 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2311 }
2312
2313 if !tcx.next_trait_solver_globally() {
2314 for (key, ty) in infcx.take_opaque_types() {
2317 let hidden_type = infcx.resolve_vars_if_possible(ty);
2318 let key = infcx.resolve_vars_if_possible(key);
2319 sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2320 }
2321 } else {
2322 let _ = infcx.take_opaque_types();
2325 }
2326
2327 Ok(())
2328}
2329
2330pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2331 tcx: TyCtxt<'tcx>,
2332 def_id: LocalDefId,
2333) -> Result<(), ErrorGuaranteed> {
2334 if !tcx.next_trait_solver_globally() {
2335 return Ok(());
2336 }
2337 let typeck_results = tcx.typeck(def_id);
2338 let param_env = tcx.param_env(def_id);
2339
2340 let typing_mode = TypingMode::borrowck(tcx, def_id);
2342 let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2343 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2344 for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2345 let predicate = fold_regions(tcx, *predicate, |_, _| {
2346 infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2347 });
2348 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2349 }
2350
2351 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2352 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs:2352",
"rustc_hir_analysis::check::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5a2be9f5f075d31e3ca5526b5b029881ce441253/compiler/rustc_hir_analysis/src/check/check.rs"),
::tracing_core::__macro_support::Option::Some(2352u32),
::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);
2353 if let TraitErrors::HasErrors(errors) = errors {
2354 Err(infcx.err_ctxt().report_fulfillment_errors(errors))
2355 } else {
2356 Ok(())
2357 }
2358}