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