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