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