1use std::cell::LazyCell;
2use std::ops::ControlFlow;
3
4use rustc_abi::{ExternAbi, FieldIdx, ScalableElt};
5use rustc_data_structures::unord::{UnordMap, UnordSet};
6use rustc_errors::codes::*;
7use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan};
8use rustc_hir as hir;
9use rustc_hir::attrs::ReprAttr::ReprPacked;
10use rustc_hir::def::{CtorKind, DefKind};
11use rustc_hir::{LangItem, Node, find_attr, intravisit};
12use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
13use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc};
14use rustc_lint_defs::builtin::{REPR_TRANSPARENT_NON_ZST_FIELDS, UNSUPPORTED_CALLING_CONVENTIONS};
15use rustc_macros::Diagnostic;
16use rustc_middle::hir::nested_filter;
17use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
18use rustc_middle::middle::stability::EvalResult;
19use rustc_middle::ty::error::TypeErrorToStringExt;
20use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
21use rustc_middle::ty::util::Discr;
22use rustc_middle::ty::{
23 AdtDef, BottomUpFolder, FnSig, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,
24 TypeVisitable, TypeVisitableExt, Unnormalized, fold_regions,
25};
26use rustc_session::lint::builtin::UNINHABITED_STATIC;
27use rustc_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, Unnormalized::new_wip(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().skip_norm_wip();
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().skip_norm_wip().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).skip_norm_wip();
let hidden_ty =
fold_regions(tcx, hidden_ty,
|re, _dbi|
match re.kind() {
ty::ReErased =>
infcx.next_region_var(RegionVariableOrigin::Misc(span)),
_ => re,
});
for (predicate, pred_span) in
tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx,
args).map(Unnormalized::skip_norm_wip) {
let predicate =
predicate.fold_with(&mut BottomUpFolder {
tcx,
ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
lt_op: |lt| lt,
ct_op: |ct| ct,
});
ocx.register_obligation(Obligation::new(tcx,
ObligationCause::new(span, def_id,
ObligationCauseCode::OpaqueTypeBound(pred_span,
definition_def_id)), param_env, predicate));
}
let misc_cause = ObligationCause::misc(span, def_id);
match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
Ok(()) => {}
Err(ty_err) => {
let ty_err = ty_err.to_string(tcx);
let guar =
tcx.dcx().span_delayed_bug(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not unify `{0}` with revealed type:\n{1}",
hidden_ty, ty_err))
}));
return Err(guar);
}
}
let predicate =
ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(),
param_env, predicate));
let errors = ocx.evaluate_obligations_error_on_ambiguity();
if !errors.is_empty() {
let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
return Err(guar);
}
let wf_tys =
ocx.assumed_wf_types_and_report_errors(param_env,
defining_use_anchor)?;
ocx.resolve_regions_and_report_errors(defining_use_anchor,
param_env, wf_tys)?;
if infcx.next_trait_solver() {
Ok(())
} else if let hir::OpaqueTyOrigin::FnReturn { .. } |
hir::OpaqueTyOrigin::AsyncFn { .. } = origin {
let _ = infcx.take_opaque_types();
Ok(())
} else {
for (mut key, mut ty) in infcx.take_opaque_types() {
ty.ty = infcx.resolve_vars_if_possible(ty.ty);
key = infcx.resolve_vars_if_possible(key);
sanity_check_found_hidden_type(tcx, key, ty)?;
}
Ok(())
}
}
}
}#[instrument(level = "debug", skip(tcx))]
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).skip_norm_wip();
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 tcx
349 .explicit_item_bounds(def_id)
350 .iter_instantiated_copied(tcx, args)
351 .map(Unnormalized::skip_norm_wip)
352 {
353 let predicate = predicate.fold_with(&mut BottomUpFolder {
354 tcx,
355 ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
356 lt_op: |lt| lt,
357 ct_op: |ct| ct,
358 });
359
360 ocx.register_obligation(Obligation::new(
361 tcx,
362 ObligationCause::new(
363 span,
364 def_id,
365 ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
366 ),
367 param_env,
368 predicate,
369 ));
370 }
371
372 let misc_cause = ObligationCause::misc(span, def_id);
373 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
377 Ok(()) => {}
378 Err(ty_err) => {
379 let ty_err = ty_err.to_string(tcx);
385 let guar = tcx.dcx().span_delayed_bug(
386 span,
387 format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
388 );
389 return Err(guar);
390 }
391 }
392
393 let predicate =
397 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
398 ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
399
400 let errors = ocx.evaluate_obligations_error_on_ambiguity();
403 if !errors.is_empty() {
404 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
405 return Err(guar);
406 }
407
408 let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
409 ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
410
411 if infcx.next_trait_solver() {
412 Ok(())
413 } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
414 origin
415 {
416 let _ = infcx.take_opaque_types();
422 Ok(())
423 } else {
424 for (mut key, mut ty) in infcx.take_opaque_types() {
426 ty.ty = infcx.resolve_vars_if_possible(ty.ty);
427 key = infcx.resolve_vars_if_possible(key);
428 sanity_check_found_hidden_type(tcx, key, ty)?;
429 }
430 Ok(())
431 }
432}
433
434fn best_definition_site_of_opaque<'tcx>(
435 tcx: TyCtxt<'tcx>,
436 opaque_def_id: LocalDefId,
437 origin: hir::OpaqueTyOrigin<LocalDefId>,
438) -> Option<(Span, LocalDefId)> {
439 struct TaitConstraintLocator<'tcx> {
440 opaque_def_id: LocalDefId,
441 tcx: TyCtxt<'tcx>,
442 }
443 impl<'tcx> TaitConstraintLocator<'tcx> {
444 fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
445 if !self.tcx.has_typeck_results(item_def_id) {
446 return ControlFlow::Continue(());
447 }
448
449 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
450 if !opaque_types_defined_by.contains(&self.opaque_def_id) {
452 return ControlFlow::Continue(());
453 }
454
455 if let Some(hidden_ty) = self
456 .tcx
457 .mir_borrowck(item_def_id)
458 .ok()
459 .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
460 {
461 ControlFlow::Break((hidden_ty.span, item_def_id))
462 } else {
463 ControlFlow::Continue(())
464 }
465 }
466 }
467 impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
468 type NestedFilter = nested_filter::All;
469 type Result = ControlFlow<(Span, LocalDefId)>;
470 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
471 self.tcx
472 }
473 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
474 intravisit::walk_expr(self, ex)
475 }
476 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
477 self.check(it.owner_id.def_id)?;
478 intravisit::walk_item(self, it)
479 }
480 fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
481 self.check(it.owner_id.def_id)?;
482 intravisit::walk_impl_item(self, it)
483 }
484 fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
485 self.check(it.owner_id.def_id)?;
486 intravisit::walk_trait_item(self, it)
487 }
488 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
489 intravisit::walk_foreign_item(self, it)
490 }
491 }
492
493 let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
494 match origin {
495 hir::OpaqueTyOrigin::FnReturn { parent, .. }
496 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
497 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
498 let impl_def_id = tcx.local_parent(parent);
499 for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
500 match assoc.kind {
501 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
502 if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
503 {
504 return Some(span);
505 }
506 }
507 ty::AssocKind::Type { .. } => {}
508 }
509 }
510
511 None
512 }
513 hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
514 tcx.hir_walk_toplevel_module(&mut locator).break_value()
515 }
516 }
517}
518
519fn sanity_check_found_hidden_type<'tcx>(
520 tcx: TyCtxt<'tcx>,
521 key: ty::OpaqueTypeKey<'tcx>,
522 mut ty: ty::ProvisionalHiddenType<'tcx>,
523) -> Result<(), ErrorGuaranteed> {
524 if ty.ty.is_ty_var() {
525 return Ok(());
527 }
528 if let &ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = ty.ty.kind() {
529 if def_id == key.def_id.to_def_id() && args == key.args {
530 return Ok(());
533 }
534 }
535 let erase_re_vars = |ty: Ty<'tcx>| {
536 fold_regions(tcx, ty, |r, _| match r.kind() {
537 RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
538 _ => r,
539 })
540 };
541 ty.ty = erase_re_vars(ty.ty);
544 let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args).skip_norm_wip();
546 let hidden_ty = erase_re_vars(hidden_ty);
547
548 if hidden_ty == ty.ty {
550 Ok(())
551 } else {
552 let span = tcx.def_span(key.def_id);
553 let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
554 Err(ty.build_mismatch_error(&other, tcx)?.emit())
555 }
556}
557
558fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
567 let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
568 let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
569 hir::GenericBound::Use(bounds, ..) => Some(bounds),
570 _ => None,
571 }) else {
572 return;
574 };
575
576 let mut expected_captures = UnordSet::default();
577 let mut shadowed_captures = UnordSet::default();
578 let mut seen_params = UnordMap::default();
579 let mut prev_non_lifetime_param = None;
580 for arg in precise_capturing_args {
581 let (hir_id, ident) = match *arg {
582 hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
583 hir_id,
584 ident,
585 ..
586 }) => {
587 if prev_non_lifetime_param.is_none() {
588 prev_non_lifetime_param = Some(ident);
589 }
590 (hir_id, ident)
591 }
592 hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
593 if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
594 tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
595 lifetime_span: ident.span,
596 name: ident.name,
597 other_span: prev_non_lifetime_param.span,
598 });
599 }
600 (hir_id, ident)
601 }
602 };
603
604 let ident = ident.normalize_to_macros_2_0();
605 if let Some(span) = seen_params.insert(ident, ident.span) {
606 tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
607 name: ident.name,
608 first_span: span,
609 second_span: ident.span,
610 });
611 }
612
613 match tcx.named_bound_var(hir_id) {
614 Some(ResolvedArg::EarlyBound(def_id)) => {
615 expected_captures.insert(def_id.to_def_id());
616
617 if let DefKind::LifetimeParam = tcx.def_kind(def_id)
623 && let Some(def_id) = tcx
624 .map_opaque_lifetime_to_parent_lifetime(def_id)
625 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
626 {
627 shadowed_captures.insert(def_id);
628 }
629 }
630 _ => {
631 tcx.dcx()
632 .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
633 }
634 }
635 }
636
637 let variances = tcx.variances_of(opaque_def_id);
638 let mut def_id = Some(opaque_def_id.to_def_id());
639 while let Some(generics) = def_id {
640 let generics = tcx.generics_of(generics);
641 def_id = generics.parent;
642
643 for param in &generics.own_params {
644 if expected_captures.contains(¶m.def_id) {
645 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!(
646 variances[param.index as usize],
647 ty::Invariant,
648 "precise captured param should be invariant"
649 );
650 continue;
651 }
652 if shadowed_captures.contains(¶m.def_id) {
656 continue;
657 }
658
659 match param.kind {
660 ty::GenericParamDefKind::Lifetime => {
661 let use_span = tcx.def_span(param.def_id);
662 let opaque_span = tcx.def_span(opaque_def_id);
663 if variances[param.index as usize] == ty::Invariant {
665 if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
666 && let Some(def_id) = tcx
667 .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
668 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
669 {
670 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
671 opaque_span,
672 use_span,
673 param_span: tcx.def_span(def_id),
674 });
675 } else {
676 if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
677 tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
678 opaque_span,
679 param_span: tcx.def_span(param.def_id),
680 });
681 } else {
682 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
687 opaque_span,
688 use_span: opaque_span,
689 param_span: use_span,
690 });
691 }
692 }
693 continue;
694 }
695 }
696 ty::GenericParamDefKind::Type { .. } => {
697 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) {
698 tcx.dcx().emit_err(errors::SelfTyNotCaptured {
700 trait_span: tcx.def_span(param.def_id),
701 opaque_span: tcx.def_span(opaque_def_id),
702 });
703 } else {
704 tcx.dcx().emit_err(errors::ParamNotCaptured {
706 param_span: tcx.def_span(param.def_id),
707 opaque_span: tcx.def_span(opaque_def_id),
708 kind: "type",
709 });
710 }
711 }
712 ty::GenericParamDefKind::Const { .. } => {
713 tcx.dcx().emit_err(errors::ParamNotCaptured {
715 param_span: tcx.def_span(param.def_id),
716 opaque_span: tcx.def_span(opaque_def_id),
717 kind: "const",
718 });
719 }
720 }
721 }
722 }
723}
724
725fn is_enum_of_nonnullable_ptr<'tcx>(
726 tcx: TyCtxt<'tcx>,
727 adt_def: AdtDef<'tcx>,
728 args: GenericArgsRef<'tcx>,
729) -> bool {
730 if adt_def.repr().inhibit_enum_layout_opt() {
731 return false;
732 }
733
734 let [var_one, var_two] = &adt_def.variants().raw[..] else {
735 return false;
736 };
737 let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
738 return false;
739 };
740 #[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(..))
741}
742
743fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
744 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
745 if match tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
746 ty::RawPtr(_, _) => false,
747 ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
748 _ => true,
749 } {
750 tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
751 }
752 }
753}
754
755pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
756 let mut res = Ok(());
757 let generics = tcx.generics_of(def_id);
758
759 for param in &generics.own_params {
760 match param.kind {
761 ty::GenericParamDefKind::Lifetime { .. } => {}
762 ty::GenericParamDefKind::Type { has_default, .. } => {
763 if has_default {
764 tcx.ensure_ok().type_of(param.def_id);
765 }
766 }
767 ty::GenericParamDefKind::Const { has_default, .. } => {
768 tcx.ensure_ok().type_of(param.def_id);
769 if has_default {
770 let ct = tcx.const_param_default(param.def_id).skip_binder();
772 if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
773 tcx.ensure_ok().type_of(uv.def);
774 }
775 }
776 }
777 }
778 }
779
780 match tcx.def_kind(def_id) {
781 DefKind::Static { .. } => {
782 tcx.ensure_ok().generics_of(def_id);
783 tcx.ensure_ok().type_of(def_id);
784 tcx.ensure_ok().predicates_of(def_id);
785
786 check_static_inhabited(tcx, def_id);
787 check_static_linkage(tcx, def_id);
788 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
789 res = res.and(wfcheck::check_static_item(
790 tcx, def_id, ty, true,
791 ));
792
793 return res;
797 }
798 DefKind::Enum => {
799 tcx.ensure_ok().generics_of(def_id);
800 tcx.ensure_ok().type_of(def_id);
801 tcx.ensure_ok().predicates_of(def_id);
802 crate::collect::lower_enum_variant_types(tcx, def_id);
803 check_enum(tcx, def_id);
804 check_variances_for_type_defn(tcx, def_id);
805 }
806 DefKind::Fn => {
807 tcx.ensure_ok().generics_of(def_id);
808 tcx.ensure_ok().type_of(def_id);
809 tcx.ensure_ok().predicates_of(def_id);
810 tcx.ensure_ok().fn_sig(def_id);
811 tcx.ensure_ok().codegen_fn_attrs(def_id);
812 if let Some(i) = tcx.intrinsic(def_id) {
813 intrinsic::check_intrinsic_type(
814 tcx,
815 def_id,
816 tcx.def_ident_span(def_id).unwrap(),
817 i.name,
818 )
819 }
820 }
821 DefKind::Impl { of_trait } => {
822 tcx.ensure_ok().generics_of(def_id);
823 tcx.ensure_ok().type_of(def_id);
824 tcx.ensure_ok().predicates_of(def_id);
825 tcx.ensure_ok().associated_items(def_id);
826 if of_trait {
827 let impl_trait_header = tcx.impl_trait_header(def_id);
828 res = res.and(tcx.ensure_result().coherent_trait(
829 impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip().def_id,
830 ));
831
832 if res.is_ok() {
833 check_impl_items_against_trait(tcx, def_id, impl_trait_header);
837 }
838 }
839 }
840 DefKind::Trait => {
841 tcx.ensure_ok().generics_of(def_id);
842 tcx.ensure_ok().trait_def(def_id);
843 tcx.ensure_ok().explicit_super_predicates_of(def_id);
844 tcx.ensure_ok().predicates_of(def_id);
845 tcx.ensure_ok().associated_items(def_id);
846 let assoc_items = tcx.associated_items(def_id);
847
848 for &assoc_item in assoc_items.in_definition_order() {
849 match assoc_item.kind {
850 ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
851 let trait_args = GenericArgs::identity_for_item(tcx, def_id);
852 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
853 tcx,
854 assoc_item,
855 assoc_item,
856 ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
857 );
858 }
859 _ => {}
860 }
861 }
862 }
863 DefKind::TraitAlias => {
864 tcx.ensure_ok().generics_of(def_id);
865 tcx.ensure_ok().explicit_implied_predicates_of(def_id);
866 tcx.ensure_ok().explicit_super_predicates_of(def_id);
867 tcx.ensure_ok().predicates_of(def_id);
868 }
869 def_kind @ (DefKind::Struct | DefKind::Union) => {
870 tcx.ensure_ok().generics_of(def_id);
871 tcx.ensure_ok().type_of(def_id);
872 tcx.ensure_ok().predicates_of(def_id);
873
874 let adt = tcx.adt_def(def_id).non_enum_variant();
875 for f in adt.fields.iter() {
876 tcx.ensure_ok().generics_of(f.did);
877 tcx.ensure_ok().type_of(f.did);
878 tcx.ensure_ok().predicates_of(f.did);
879 }
880
881 if let Some((_, ctor_def_id)) = adt.ctor {
882 crate::collect::lower_variant_ctor(tcx, ctor_def_id.expect_local());
883 }
884 match def_kind {
885 DefKind::Struct => check_struct(tcx, def_id),
886 DefKind::Union => check_union(tcx, def_id),
887 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
888 }
889 check_variances_for_type_defn(tcx, def_id);
890 }
891 DefKind::OpaqueTy => {
892 check_opaque_precise_captures(tcx, def_id);
893
894 let origin = tcx.local_opaque_ty_origin(def_id);
895 if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
896 | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
897 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
898 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
899 {
900 } else {
902 check_opaque(tcx, def_id);
903 }
904
905 tcx.ensure_ok().predicates_of(def_id);
906 tcx.ensure_ok().explicit_item_bounds(def_id);
907 tcx.ensure_ok().explicit_item_self_bounds(def_id);
908 if tcx.is_conditionally_const(def_id) {
909 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
910 tcx.ensure_ok().const_conditions(def_id);
911 }
912
913 return res;
917 }
918 DefKind::Const { .. } => {
919 tcx.ensure_ok().generics_of(def_id);
920 tcx.ensure_ok().type_of(def_id);
921 tcx.ensure_ok().predicates_of(def_id);
922
923 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
924 let ty = tcx.type_of(def_id).instantiate_identity();
925 let ty_span = tcx.ty_span(def_id);
926 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
927 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
928 wfcx.register_bound(
929 traits::ObligationCause::new(
930 ty_span,
931 def_id,
932 ObligationCauseCode::SizedConstOrStatic,
933 ),
934 tcx.param_env(def_id),
935 ty,
936 tcx.require_lang_item(LangItem::Sized, ty_span),
937 );
938 check_where_clauses(wfcx, def_id);
939
940 if tcx.is_type_const(def_id) {
941 wfcheck::check_type_const(wfcx, def_id, ty, true)?;
942 }
943 Ok(())
944 }));
945
946 return res;
950 }
951 DefKind::TyAlias => {
952 tcx.ensure_ok().generics_of(def_id);
953 tcx.ensure_ok().type_of(def_id);
954 tcx.ensure_ok().predicates_of(def_id);
955 check_type_alias_type_params_are_used(tcx, def_id);
956 let ty = tcx.type_of(def_id).instantiate_identity();
957 let span = tcx.def_span(def_id);
958 if tcx.type_alias_is_lazy(def_id) {
959 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
960 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
961 wfcx.register_wf_obligation(
962 span,
963 Some(WellFormedLoc::Ty(def_id)),
964 item_ty.into(),
965 );
966 check_where_clauses(wfcx, def_id);
967 Ok(())
968 }));
969 check_variances_for_type_defn(tcx, def_id);
970 } else {
971 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
972 if let Some(unnormalized_obligations) = wfcx.unnormalized_obligations(span, ty.skip_norm_wip())
983 {
984 let filtered_obligations =
985 unnormalized_obligations.into_iter().filter(|o| {
986 #[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(),
987 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
988 if matches!(ct.kind(), ty::ConstKind::Param(..)))
989 });
990 wfcx.ocx.register_obligations(filtered_obligations)
991 }
992 Ok(())
993 }));
994 }
995
996 return res;
1000 }
1001 DefKind::ForeignMod => {
1002 let it = tcx.hir_expect_item(def_id);
1003 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
1004 return Ok(());
1005 };
1006
1007 check_abi(tcx, it.hir_id(), it.span, abi);
1008
1009 for &item in items {
1010 let def_id = item.owner_id.def_id;
1011
1012 let generics = tcx.generics_of(def_id);
1013 let own_counts = generics.own_counts();
1014 if generics.own_params.len() - own_counts.lifetimes != 0 {
1015 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
1016 (_, 0) => ("type", "types", Some("u32")),
1017 (0, _) => ("const", "consts", None),
1020 _ => ("type or const", "types or consts", None),
1021 };
1022 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) {
1023 "externally implementable items"
1024 } else {
1025 "foreign items"
1026 };
1027
1028 let span = tcx.def_span(def_id);
1029 {
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!(
1030 tcx.dcx(),
1031 span,
1032 E0044,
1033 "{name} may not have {kinds} parameters",
1034 )
1035 .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"))
1036 .with_help(
1037 ::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!(
1040 "replace the {} parameters with concrete {}{}",
1041 kinds,
1042 kinds_pl,
1043 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
1044 ),
1045 )
1046 .emit();
1047 }
1048
1049 tcx.ensure_ok().generics_of(def_id);
1050 tcx.ensure_ok().type_of(def_id);
1051 tcx.ensure_ok().predicates_of(def_id);
1052 if tcx.is_conditionally_const(def_id) {
1053 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1054 tcx.ensure_ok().const_conditions(def_id);
1055 }
1056 match tcx.def_kind(def_id) {
1057 DefKind::Fn => {
1058 tcx.ensure_ok().codegen_fn_attrs(def_id);
1059 tcx.ensure_ok().fn_sig(def_id);
1060 let item = tcx.hir_foreign_item(item);
1061 let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1062 check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1063 }
1064 DefKind::Static { .. } => {
1065 tcx.ensure_ok().codegen_fn_attrs(def_id);
1066 }
1067 _ => (),
1068 }
1069 }
1070 }
1071 DefKind::Closure => {
1072 tcx.ensure_ok().codegen_fn_attrs(def_id);
1076 return res;
1084 }
1085 DefKind::AssocFn => {
1086 tcx.ensure_ok().codegen_fn_attrs(def_id);
1087 tcx.ensure_ok().type_of(def_id);
1088 tcx.ensure_ok().fn_sig(def_id);
1089 tcx.ensure_ok().predicates_of(def_id);
1090 res = res.and(check_associated_item(tcx, def_id));
1091 let assoc_item = tcx.associated_item(def_id);
1092 match assoc_item.container {
1093 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1094 ty::AssocContainer::Trait => {
1095 res = res.and(check_trait_item(tcx, def_id));
1096 }
1097 }
1098
1099 return res;
1103 }
1104 DefKind::AssocConst { .. } => {
1105 tcx.ensure_ok().type_of(def_id);
1106 tcx.ensure_ok().predicates_of(def_id);
1107 res = res.and(check_associated_item(tcx, def_id));
1108 let assoc_item = tcx.associated_item(def_id);
1109 match assoc_item.container {
1110 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1111 ty::AssocContainer::Trait => {
1112 res = res.and(check_trait_item(tcx, def_id));
1113 }
1114 }
1115
1116 return res;
1120 }
1121 DefKind::AssocTy => {
1122 tcx.ensure_ok().predicates_of(def_id);
1123 res = res.and(check_associated_item(tcx, def_id));
1124
1125 let assoc_item = tcx.associated_item(def_id);
1126 let has_type = match assoc_item.container {
1127 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1128 ty::AssocContainer::Trait => {
1129 tcx.ensure_ok().explicit_item_bounds(def_id);
1130 tcx.ensure_ok().explicit_item_self_bounds(def_id);
1131 if tcx.is_conditionally_const(def_id) {
1132 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1133 tcx.ensure_ok().const_conditions(def_id);
1134 }
1135 res = res.and(check_trait_item(tcx, def_id));
1136 assoc_item.defaultness(tcx).has_value()
1137 }
1138 };
1139 if has_type {
1140 tcx.ensure_ok().type_of(def_id);
1141 }
1142
1143 return res;
1147 }
1148
1149 DefKind::AnonConst | DefKind::InlineConst => return res,
1153 _ => {}
1154 }
1155 let node = tcx.hir_node_by_def_id(def_id);
1156 res.and(match node {
1157 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"),
1158 hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1159 hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1160 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", node)));
}unreachable!("{node:?}"),
1161 })
1162}
1163
1164pub(super) fn check_specialization_validity<'tcx>(
1165 tcx: TyCtxt<'tcx>,
1166 trait_def: &ty::TraitDef,
1167 trait_item: ty::AssocItem,
1168 impl_id: DefId,
1169 impl_item: DefId,
1170) {
1171 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1172 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1173 if parent.is_from_trait() {
1174 None
1175 } else {
1176 Some((parent, parent.item(tcx, trait_item.def_id)))
1177 }
1178 });
1179
1180 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1181 match parent_item {
1182 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1185 Some(Err(parent_impl.def_id()))
1186 }
1187
1188 Some(_) => Some(Ok(())),
1190
1191 None => {
1195 if tcx.defaultness(parent_impl.def_id()).is_default() {
1196 None
1197 } else {
1198 Some(Err(parent_impl.def_id()))
1199 }
1200 }
1201 }
1202 });
1203
1204 let result = opt_result.unwrap_or(Ok(()));
1207
1208 if let Err(parent_impl) = result {
1209 if !tcx.is_impl_trait_in_trait(impl_item) {
1210 let span = tcx.def_span(impl_item);
1211 let ident = tcx.item_ident(impl_item);
1212
1213 let err = match tcx.span_of_impl(parent_impl) {
1214 Ok(sp) => errors::ImplNotMarkedDefault::Ok { span, ident, ok_label: sp },
1215 Err(cname) => errors::ImplNotMarkedDefault::Err { span, ident, cname },
1216 };
1217
1218 tcx.dcx().emit_err(err);
1219 } else {
1220 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"));
1221 }
1222 }
1223}
1224
1225fn check_overriding_final_trait_item<'tcx>(
1226 tcx: TyCtxt<'tcx>,
1227 trait_item: ty::AssocItem,
1228 impl_item: ty::AssocItem,
1229) {
1230 if trait_item.defaultness(tcx).is_final() {
1231 tcx.dcx().emit_err(errors::OverridingFinalTraitFunction {
1232 impl_span: tcx.def_span(impl_item.def_id),
1233 trait_span: tcx.def_span(trait_item.def_id),
1234 ident: tcx.item_ident(impl_item.def_id),
1235 });
1236 }
1237}
1238
1239fn check_impl_items_against_trait<'tcx>(
1240 tcx: TyCtxt<'tcx>,
1241 impl_id: LocalDefId,
1242 impl_trait_header: ty::ImplTraitHeader<'tcx>,
1243) {
1244 let trait_ref = impl_trait_header.trait_ref.instantiate_identity().skip_norm_wip();
1245 if trait_ref.references_error() {
1249 return;
1250 }
1251
1252 let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1253
1254 match impl_trait_header.polarity {
1256 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1257 ty::ImplPolarity::Negative => {
1258 if let [first_item_ref, ..] = *impl_item_refs {
1259 let first_item_span = tcx.def_span(first_item_ref);
1260 {
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!(
1261 tcx.dcx(),
1262 first_item_span,
1263 E0749,
1264 "negative impls cannot have any items"
1265 )
1266 .emit();
1267 }
1268 return;
1269 }
1270 }
1271
1272 let trait_def = tcx.trait_def(trait_ref.def_id);
1273
1274 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1275
1276 for &impl_item in impl_item_refs {
1277 let ty_impl_item = tcx.associated_item(impl_item);
1278 let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1279 Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1280 Err(ErrorGuaranteed { .. }) => continue,
1281 };
1282
1283 let res = tcx.ensure_result().compare_impl_item(impl_item.expect_local());
1284 if res.is_ok() {
1285 match ty_impl_item.kind {
1286 ty::AssocKind::Fn { .. } => {
1287 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1288 tcx,
1289 ty_impl_item,
1290 ty_trait_item,
1291 tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1292 .instantiate_identity()
1293 .skip_norm_wip(),
1294 );
1295 }
1296 ty::AssocKind::Const { .. } => {}
1297 ty::AssocKind::Type { .. } => {}
1298 }
1299 }
1300
1301 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1302 tcx.emit_node_span_lint(
1303 rustc_lint_defs::builtin::DEAD_CODE,
1304 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1305 tcx.def_span(ty_impl_item.def_id),
1306 errors::UselessImplItem,
1307 )
1308 }
1309
1310 check_specialization_validity(
1311 tcx,
1312 trait_def,
1313 ty_trait_item,
1314 impl_id.to_def_id(),
1315 impl_item,
1316 );
1317
1318 check_overriding_final_trait_item(tcx, ty_trait_item, ty_impl_item);
1319 }
1320
1321 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1322 let mut missing_items = Vec::new();
1324
1325 let mut must_implement_one_of: Option<&[Ident]> =
1326 trait_def.must_implement_one_of.as_deref();
1327
1328 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1329 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1330
1331 let is_implemented = leaf_def
1332 .as_ref()
1333 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1334
1335 if !is_implemented
1336 && tcx.defaultness(impl_id).is_final()
1337 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1339 {
1340 missing_items.push(tcx.associated_item(trait_item_id));
1341 }
1342
1343 let is_implemented_here =
1345 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1346
1347 if !is_implemented_here {
1348 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1349 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1350 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1351 tcx,
1352 full_impl_span,
1353 trait_item_id,
1354 feature,
1355 reason,
1356 issue,
1357 ),
1358
1359 EvalResult::Allow | EvalResult::Unmarked => {}
1361 }
1362 }
1363
1364 if let Some(required_items) = &must_implement_one_of {
1365 if is_implemented_here {
1366 let trait_item = tcx.associated_item(trait_item_id);
1367 if required_items.contains(&trait_item.ident(tcx)) {
1368 must_implement_one_of = None;
1369 }
1370 }
1371 }
1372
1373 if let Some(leaf_def) = &leaf_def
1374 && !leaf_def.is_final()
1375 && let def_id = leaf_def.item.def_id
1376 && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1377 {
1378 let def_kind = tcx.def_kind(def_id);
1379 let descr = tcx.def_kind_descr(def_kind, def_id);
1380 let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1381 (
1382 ::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"),
1383 "async functions in traits",
1384 )
1385 } else {
1386 (
1387 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} with return-position `impl Trait` in trait cannot be specialized",
descr))
})format!(
1388 "{descr} with return-position `impl Trait` in trait cannot be specialized"
1389 ),
1390 "return position `impl Trait` in traits",
1391 )
1392 };
1393 tcx.dcx()
1394 .struct_span_err(tcx.def_span(def_id), msg)
1395 .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!(
1396 "specialization behaves in inconsistent and surprising ways with \
1397 {feature}, and for now is disallowed"
1398 ))
1399 .emit();
1400 }
1401 }
1402
1403 if !missing_items.is_empty() {
1404 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1405 missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1406 }
1407
1408 if let Some(missing_items) = must_implement_one_of {
1409 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);
1410
1411 missing_items_must_implement_one_of_err(
1412 tcx,
1413 tcx.def_span(impl_id),
1414 missing_items,
1415 attr_span,
1416 );
1417 }
1418 }
1419}
1420
1421fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1422 let t = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1423 if let ty::Adt(def, args) = t.kind()
1424 && def.is_struct()
1425 {
1426 let fields = &def.non_enum_variant().fields;
1427 if fields.is_empty() {
1428 {
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();
1429 return;
1430 }
1431
1432 let array_field = &fields[FieldIdx::ZERO];
1433 let array_ty = array_field.ty(tcx, args);
1434 let ty::Array(element_ty, len_const) = array_ty.kind() else {
1435 {
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!(
1436 tcx.dcx(),
1437 sp,
1438 E0076,
1439 "SIMD vector's only field must be an array"
1440 )
1441 .with_span_label(tcx.def_span(array_field.did), "not an array")
1442 .emit();
1443 return;
1444 };
1445
1446 if let Some(second_field) = fields.get(FieldIdx::ONE) {
1447 {
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")
1448 .with_span_label(tcx.def_span(second_field.did), "excess field")
1449 .emit();
1450 return;
1451 }
1452
1453 if let Some(len) = len_const.try_to_target_usize(tcx) {
1458 if len == 0 {
1459 {
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();
1460 return;
1461 } else if len > MAX_SIMD_LANES {
1462 {
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!(
1463 tcx.dcx(),
1464 sp,
1465 E0075,
1466 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1467 )
1468 .emit();
1469 return;
1470 }
1471 }
1472
1473 match element_ty.kind() {
1478 ty::Param(_) => (), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), _ => {
1481 {
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!(
1482 tcx.dcx(),
1483 sp,
1484 E0077,
1485 "SIMD vector element type should be a \
1486 primitive scalar (integer/float/pointer) type"
1487 )
1488 .emit();
1489 return;
1490 }
1491 }
1492 }
1493}
1494
1495#[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(1495u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::check::check"),
::tracing_core::field::FieldSet::new(&["span", "def_id",
"scalable"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scalable)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let ty =
tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
let ty::Adt(def, args) = ty.kind() else { return };
if !def.is_struct() {
tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
return;
}
let fields = &def.non_enum_variant().fields;
match scalable {
ScalableElt::ElementCount(..) if fields.is_empty() => {
let mut err =
tcx.dcx().struct_span_err(span,
"scalable vectors must have a single field");
err.help("scalable vector types' only field must be a primitive scalar type");
err.emit();
return;
}
ScalableElt::ElementCount(..) if fields.len() >= 2 => {
tcx.dcx().struct_span_err(span,
"scalable vectors cannot have multiple fields").emit();
return;
}
ScalableElt::Container if fields.is_empty() => {
let mut err =
tcx.dcx().struct_span_err(span,
"scalable vector tuples must have at least one field");
err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
err.emit();
return;
}
ScalableElt::Container if fields.len() > 8 => {
let mut err =
tcx.dcx().struct_span_err(span,
"scalable vector tuples can have at most eight fields");
err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
err.emit();
return;
}
_ => {}
}
match scalable {
ScalableElt::ElementCount(..) => {
let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args);
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")]
1496fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {
1497 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1498 let ty::Adt(def, args) = ty.kind() else { return };
1499 if !def.is_struct() {
1500 tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
1501 return;
1502 }
1503
1504 let fields = &def.non_enum_variant().fields;
1505 match scalable {
1506 ScalableElt::ElementCount(..) if fields.is_empty() => {
1507 let mut err =
1508 tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1509 err.help("scalable vector types' only field must be a primitive scalar type");
1510 err.emit();
1511 return;
1512 }
1513 ScalableElt::ElementCount(..) if fields.len() >= 2 => {
1514 tcx.dcx().struct_span_err(span, "scalable vectors cannot have multiple fields").emit();
1515 return;
1516 }
1517 ScalableElt::Container if fields.is_empty() => {
1518 let mut err = tcx
1519 .dcx()
1520 .struct_span_err(span, "scalable vector tuples must have at least one field");
1521 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1522 err.emit();
1523 return;
1524 }
1525 ScalableElt::Container if fields.len() > 8 => {
1526 let mut err = tcx
1527 .dcx()
1528 .struct_span_err(span, "scalable vector tuples can have at most eight fields");
1529 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1530 err.emit();
1531 return;
1532 }
1533 _ => {}
1534 }
1535
1536 match scalable {
1537 ScalableElt::ElementCount(..) => {
1538 let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args);
1539
1540 match element_ty.kind() {
1544 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
1545 _ => {
1546 let mut err = tcx.dcx().struct_span_err(
1547 span,
1548 "element type of a scalable vector must be a primitive scalar",
1549 );
1550 err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
1551 err.emit();
1552 }
1553 }
1554 }
1555 ScalableElt::Container => {
1556 let mut prev_field_ty = None;
1557 for field in fields.iter() {
1558 let element_ty = field.ty(tcx, args);
1559 if let ty::Adt(def, _) = element_ty.kind()
1560 && def.repr().scalable()
1561 {
1562 match def
1563 .repr()
1564 .scalable
1565 .expect("`repr().scalable.is_some()` != `repr().scalable()`")
1566 {
1567 ScalableElt::ElementCount(_) => { }
1568 ScalableElt::Container => {
1569 tcx.dcx().span_err(
1570 tcx.def_span(field.did),
1571 "scalable vector structs cannot contain other scalable vector structs",
1572 );
1573 break;
1574 }
1575 }
1576 } else {
1577 tcx.dcx().span_err(
1578 tcx.def_span(field.did),
1579 "scalable vector structs can only have scalable vector fields",
1580 );
1581 break;
1582 }
1583
1584 if let Some(prev_ty) = prev_field_ty.replace(element_ty)
1585 && prev_ty != element_ty
1586 {
1587 tcx.dcx().span_err(
1588 tcx.def_span(field.did),
1589 "all fields in a scalable vector struct must be the same type",
1590 );
1591 break;
1592 }
1593 }
1594 }
1595 }
1596}
1597
1598pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1599 let repr = def.repr();
1600 if repr.packed() {
1601 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) {
1602 for (r, _) in reprs {
1603 if let ReprPacked(pack) = r
1604 && let Some(repr_pack) = repr.pack
1605 && pack != &repr_pack
1606 {
1607 {
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!(
1608 tcx.dcx(),
1609 sp,
1610 E0634,
1611 "type has conflicting packed representation hints"
1612 )
1613 .emit();
1614 }
1615 }
1616 }
1617 if repr.align.is_some() {
1618 {
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!(
1619 tcx.dcx(),
1620 sp,
1621 E0587,
1622 "type has conflicting packed and align representation hints"
1623 )
1624 .emit();
1625 } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut ::alloc::vec::Vec::new()vec![]) {
1626 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!(
1627 tcx.dcx(),
1628 sp,
1629 E0588,
1630 "packed type cannot transitively contain a `#[repr(align)]` type"
1631 );
1632
1633 err.span_note(
1634 tcx.def_span(def_spans[0].0),
1635 ::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)),
1636 );
1637
1638 if def_spans.len() > 2 {
1639 let mut first = true;
1640 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1641 let ident = tcx.item_name(*adt_def);
1642 err.span_note(
1643 *span,
1644 if first {
1645 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` contains a field of type `{1}`",
tcx.type_of(def.did()).instantiate_identity().skip_norm_wip(),
ident))
})format!(
1646 "`{}` contains a field of type `{}`",
1647 tcx.type_of(def.did()).instantiate_identity().skip_norm_wip(),
1648 ident
1649 )
1650 } else {
1651 ::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}`")
1652 },
1653 );
1654 first = false;
1655 }
1656 }
1657
1658 err.emit();
1659 }
1660 }
1661}
1662
1663pub(super) fn check_packed_inner(
1664 tcx: TyCtxt<'_>,
1665 def_id: DefId,
1666 stack: &mut Vec<DefId>,
1667) -> Option<Vec<(DefId, Span)>> {
1668 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
1669 if def.is_struct() || def.is_union() {
1670 if def.repr().align.is_some() {
1671 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)]);
1672 }
1673
1674 stack.push(def_id);
1675 for field in &def.non_enum_variant().fields {
1676 if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1677 && !stack.contains(&def.did())
1678 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1679 {
1680 defs.push((def.did(), field.ident(tcx).span));
1681 return Some(defs);
1682 }
1683 }
1684 stack.pop();
1685 }
1686 }
1687
1688 None
1689}
1690
1691pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1692 struct ZeroSizedFieldReprTransparentIncompatibility<'tcx> {
1693 unsuited: UnsuitedInfo<'tcx>,
1694 }
1695
1696 impl<'a, 'tcx> Diagnostic<'a, ()> for ZeroSizedFieldReprTransparentIncompatibility<'tcx> {
1697 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1698 let Self { unsuited } = self;
1699 let (title, note) = match unsuited.reason {
1700 UnsuitedReason::NonExhaustive => (
1701 "external non-exhaustive types",
1702 "is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future.",
1703 ),
1704 UnsuitedReason::PrivateField => (
1705 "external types with private fields",
1706 "contains private fields, so it could become non-zero-sized in the future.",
1707 ),
1708 UnsuitedReason::ReprC => (
1709 "`repr(C)` types",
1710 "is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets.",
1711 ),
1712 };
1713 Diag::new(
1714 dcx,
1715 level,
1716 ::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}"),
1717 )
1718 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this field contains `{0}`, which {1}",
unsuited.ty, note))
})format!(
1719 "this field contains `{field_ty}`, which {note}",
1720 field_ty = unsuited.ty,
1721 ))
1722 }
1723 }
1724
1725 if !adt.repr().transparent() {
1726 return;
1727 }
1728
1729 if adt.is_union() && !tcx.features().transparent_unions() {
1730 feature_err(
1731 &tcx.sess,
1732 sym::transparent_unions,
1733 tcx.def_span(adt.did()),
1734 "transparent unions are unstable",
1735 )
1736 .emit();
1737 }
1738
1739 if adt.variants().len() != 1 {
1740 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1741 return;
1743 }
1744
1745 let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1746 struct FieldInfo<'tcx> {
1748 span: Span,
1749 trivial: bool,
1750 ty: Ty<'tcx>,
1751 }
1752
1753 let field_infos = adt.all_fields().map(|field| {
1754 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1755 let layout = tcx.layout_of(typing_env.as_query_input(ty));
1756 let span = tcx.hir_span_if_local(field.did).unwrap();
1758 let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1759 FieldInfo { span, trivial, ty }
1760 });
1761
1762 let non_trivial_fields = field_infos
1763 .clone()
1764 .filter_map(|field| if !field.trivial { Some(field.span) } else { None });
1765 let non_trivial_count = non_trivial_fields.clone().count();
1766 if non_trivial_count >= 2 {
1767 bad_non_zero_sized_fields(
1768 tcx,
1769 adt,
1770 non_trivial_count,
1771 non_trivial_fields,
1772 tcx.def_span(adt.did()),
1773 );
1774 return;
1775 }
1776
1777 struct UnsuitedInfo<'tcx> {
1780 ty: Ty<'tcx>,
1782 reason: UnsuitedReason,
1783 }
1784 enum UnsuitedReason {
1785 NonExhaustive,
1786 PrivateField,
1787 ReprC,
1788 }
1789
1790 fn check_unsuited<'tcx>(
1791 tcx: TyCtxt<'tcx>,
1792 typing_env: ty::TypingEnv<'tcx>,
1793 ty: Ty<'tcx>,
1794 ) -> ControlFlow<UnsuitedInfo<'tcx>> {
1795 let ty =
1797 tcx.try_normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty)).unwrap_or(ty);
1798 match ty.kind() {
1799 ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1800 ty::Array(ty, _) => check_unsuited(tcx, typing_env, *ty),
1801 ty::Adt(def, args) => {
1802 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(_)) {
1803 let non_exhaustive = def.is_variant_list_non_exhaustive()
1804 || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1805 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1806 if non_exhaustive || has_priv {
1807 return ControlFlow::Break(UnsuitedInfo {
1808 ty,
1809 reason: if non_exhaustive {
1810 UnsuitedReason::NonExhaustive
1811 } else {
1812 UnsuitedReason::PrivateField
1813 },
1814 });
1815 }
1816 }
1817 if def.repr().c() {
1818 return ControlFlow::Break(UnsuitedInfo { ty, reason: UnsuitedReason::ReprC });
1819 }
1820 def.all_fields()
1821 .map(|field| field.ty(tcx, args))
1822 .try_for_each(|t| check_unsuited(tcx, typing_env, t))
1823 }
1824 _ => ControlFlow::Continue(()),
1825 }
1826 }
1827
1828 let mut prev_unsuited_1zst = false;
1829 for field in field_infos {
1830 if field.trivial
1831 && let Some(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1832 {
1833 if non_trivial_count > 0 || prev_unsuited_1zst {
1836 tcx.emit_node_span_lint(
1837 REPR_TRANSPARENT_NON_ZST_FIELDS,
1838 tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1839 field.span,
1840 ZeroSizedFieldReprTransparentIncompatibility { unsuited },
1841 );
1842 } else {
1843 prev_unsuited_1zst = true;
1844 }
1845 }
1846 }
1847}
1848
1849#[allow(trivial_numeric_casts)]
1850fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1851 let def = tcx.adt_def(def_id);
1852 def.destructor(tcx); if def.variants().is_empty() {
1855 {
{
'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 } => {
1856 struct_span_code_err!(
1857 tcx.dcx(),
1858 reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1859 E0084,
1860 "unsupported representation for zero-variant enum"
1861 )
1862 .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1863 .emit();
1864 });
1865 }
1866
1867 for v in def.variants() {
1868 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1869 tcx.ensure_ok().typeck(discr_def_id.expect_local());
1870 }
1871 }
1872
1873 if def.repr().int.is_none() {
1874 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));
1875 let get_disr = |var: &ty::VariantDef| match var.discr {
1876 ty::VariantDiscr::Explicit(disr) => Some(disr),
1877 ty::VariantDiscr::Relative(_) => None,
1878 };
1879
1880 let non_unit = def.variants().iter().find(|var| !is_unit(var));
1881 let disr_unit =
1882 def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1883 let disr_non_unit =
1884 def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1885
1886 if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1887 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!(
1888 tcx.dcx(),
1889 tcx.def_span(def_id),
1890 E0732,
1891 "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1892 );
1893 if let Some(disr_non_unit) = disr_non_unit {
1894 err.span_label(
1895 tcx.def_span(disr_non_unit),
1896 "explicit discriminant on non-unit variant specified here",
1897 );
1898 } else {
1899 err.span_label(
1900 tcx.def_span(disr_unit.unwrap()),
1901 "explicit discriminant specified here",
1902 );
1903 err.span_label(
1904 tcx.def_span(non_unit.unwrap().def_id),
1905 "non-unit discriminant declared here",
1906 );
1907 }
1908 err.emit();
1909 }
1910 }
1911
1912 detect_discriminant_duplicate(tcx, def);
1913 check_transparent(tcx, def);
1914}
1915
1916fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1918 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1921 let var = adt.variant(idx); let (span, display_discr) = match var.discr {
1923 ty::VariantDiscr::Explicit(discr_def_id) => {
1924 if let hir::Node::AnonConst(expr) =
1926 tcx.hir_node_by_def_id(discr_def_id.expect_local())
1927 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1928 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1929 && *lit_value != dis.val
1930 {
1931 (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}`)"))
1932 } else {
1933 (tcx.def_span(discr_def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`"))
1935 }
1936 }
1937 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`")),
1939 ty::VariantDiscr::Relative(distance_to_explicit) => {
1940 if let Some(explicit_idx) =
1945 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1946 {
1947 let explicit_variant = adt.variant(explicit_idx);
1948 let ve_ident = var.name;
1949 let ex_ident = explicit_variant.name;
1950 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1951
1952 err.span_label(
1953 tcx.def_span(explicit_variant.def_id),
1954 ::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!(
1955 "discriminant for `{ve_ident}` incremented from this startpoint \
1956 (`{ex_ident}` + {distance_to_explicit} {sp} later \
1957 => `{ve_ident}` = {dis})"
1958 ),
1959 );
1960 }
1961
1962 (tcx.def_span(var.def_id), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", dis))
})format!("`{dis}`"))
1963 }
1964 };
1965
1966 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} assigned here", display_discr))
})format!("{display_discr} assigned here"));
1967 };
1968
1969 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1970
1971 let mut i = 0;
1978 while i < discrs.len() {
1979 let var_i_idx = discrs[i].0;
1980 let mut error: Option<Diag<'_, _>> = None;
1981
1982 let mut o = i + 1;
1983 while o < discrs.len() {
1984 let var_o_idx = discrs[o].0;
1985
1986 if discrs[i].1.val == discrs[o].1.val {
1987 let err = error.get_or_insert_with(|| {
1988 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!(
1989 tcx.dcx(),
1990 tcx.def_span(adt.did()),
1991 E0081,
1992 "discriminant value `{}` assigned more than once",
1993 discrs[i].1,
1994 );
1995
1996 report(discrs[i].1, var_i_idx, &mut ret);
1997
1998 ret
1999 });
2000
2001 report(discrs[o].1, var_o_idx, err);
2002
2003 discrs[o] = *discrs.last().unwrap();
2005 discrs.pop();
2006 } else {
2007 o += 1;
2008 }
2009 }
2010
2011 if let Some(e) = error {
2012 e.emit();
2013 }
2014
2015 i += 1;
2016 }
2017}
2018
2019fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
2020 if tcx.type_alias_is_lazy(def_id) {
2021 return;
2024 }
2025
2026 let generics = tcx.generics_of(def_id);
2027 if generics.own_counts().types == 0 {
2028 return;
2029 }
2030
2031 let ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
2032 if ty.references_error() {
2033 return;
2035 }
2036
2037 let bounded_params = LazyCell::new(|| {
2039 tcx.explicit_predicates_of(def_id)
2040 .predicates
2041 .iter()
2042 .filter_map(|(predicate, span)| {
2043 let bounded_ty = match predicate.kind().skip_binder() {
2044 ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
2045 ty::ClauseKind::TypeOutlives(pred) => pred.0,
2046 _ => return None,
2047 };
2048 if let ty::Param(param) = bounded_ty.kind() {
2049 Some((param.index, span))
2050 } else {
2051 None
2052 }
2053 })
2054 .collect::<FxIndexMap<_, _>>()
2060 });
2061
2062 let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
2063 for leaf in ty.walk() {
2064 if let GenericArgKind::Type(leaf_ty) = leaf.kind()
2065 && let ty::Param(param) = leaf_ty.kind()
2066 {
2067 {
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:2067",
"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(2067u32),
::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);
2068 params_used.insert(param.index);
2069 }
2070 }
2071
2072 for param in &generics.own_params {
2073 if !params_used.contains(param.index)
2074 && let ty::GenericParamDefKind::Type { .. } = param.kind
2075 {
2076 let span = tcx.def_span(param.def_id);
2077 let param_name = Ident::new(param.name, span);
2078
2079 let has_explicit_bounds = bounded_params.is_empty()
2083 || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span);
2084 let const_param_help = !has_explicit_bounds;
2085
2086 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2087 span,
2088 param_name,
2089 param_def_kind: tcx.def_descr(param.def_id),
2090 help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
2091 usage_spans: ::alloc::vec::Vec::new()vec![],
2092 const_param_help,
2093 });
2094 diag.code(E0091);
2095 diag.emit();
2096 }
2097 }
2098}
2099
2100fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
2109 let span = tcx.def_span(opaque_def_id);
2110 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");
2111
2112 let mut label = false;
2113 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
2114 let typeck_results = tcx.typeck(def_id);
2115 if visitor
2116 .returns
2117 .iter()
2118 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
2119 .all(|ty| #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Never => true,
_ => false,
}matches!(ty.kind(), ty::Never))
2120 {
2121 let spans = visitor
2122 .returns
2123 .iter()
2124 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
2125 .map(|expr| expr.span)
2126 .collect::<Vec<Span>>();
2127 let span_len = spans.len();
2128 if span_len == 1 {
2129 err.span_label(spans[0], "this returned value is of `!` type");
2130 } else {
2131 let mut multispan: MultiSpan = spans.clone().into();
2132 for span in spans {
2133 multispan.push_span_label(span, "this returned value is of `!` type");
2134 }
2135 err.span_note(multispan, "these returned values have a concrete \"never\" type");
2136 }
2137 err.help("this error will resolve once the item's body returns a concrete type");
2138 } else {
2139 let mut seen = FxHashSet::default();
2140 seen.insert(span);
2141 err.span_label(span, "recursive opaque type");
2142 label = true;
2143 for (sp, ty) in visitor
2144 .returns
2145 .iter()
2146 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
2147 .filter(|(_, ty)| !#[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Never => true,
_ => false,
}matches!(ty.kind(), ty::Never))
2148 {
2149 #[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)]
2150 struct OpaqueTypeCollector {
2151 opaques: Vec<DefId>,
2152 closures: Vec<DefId>,
2153 }
2154 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
2155 fn visit_ty(&mut self, t: Ty<'tcx>) {
2156 match *t.kind() {
2157 ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id: def }, .. }) => {
2158 self.opaques.push(def);
2159 }
2160 ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
2161 self.closures.push(def_id);
2162 t.super_visit_with(self);
2163 }
2164 _ => t.super_visit_with(self),
2165 }
2166 }
2167 }
2168
2169 let mut visitor = OpaqueTypeCollector::default();
2170 ty.visit_with(&mut visitor);
2171 for def_id in visitor.opaques {
2172 let ty_span = tcx.def_span(def_id);
2173 if !seen.contains(&ty_span) {
2174 let descr = if ty.is_opaque() { "opaque " } else { "" };
2175 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}`"));
2176 seen.insert(ty_span);
2177 }
2178 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}`"));
2179 }
2180
2181 for closure_def_id in visitor.closures {
2182 let Some(closure_local_did) = closure_def_id.as_local() else {
2183 continue;
2184 };
2185 let typeck_results = tcx.typeck(closure_local_did);
2186
2187 let mut label_match = |ty: Ty<'_>, span| {
2188 for arg in ty.walk() {
2189 if let ty::GenericArgKind::Type(ty) = arg.kind()
2190 && let ty::Alias(ty::AliasTy {
2191 kind: ty::Opaque { def_id: captured_def_id },
2192 ..
2193 }) = *ty.kind()
2194 && captured_def_id == opaque_def_id.to_def_id()
2195 {
2196 err.span_label(
2197 span,
2198 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} captures itself here",
tcx.def_descr(closure_def_id)))
})format!(
2199 "{} captures itself here",
2200 tcx.def_descr(closure_def_id)
2201 ),
2202 );
2203 }
2204 }
2205 };
2206
2207 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2209 {
2210 label_match(capture.place.ty(), capture.get_path_span(tcx));
2211 }
2212 if tcx.is_coroutine(closure_def_id)
2214 && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2215 {
2216 for interior_ty in &coroutine_layout.field_tys {
2217 label_match(interior_ty.ty, interior_ty.source_info.span);
2218 }
2219 }
2220 }
2221 }
2222 }
2223 }
2224 if !label {
2225 err.span_label(span, "cannot resolve opaque type");
2226 }
2227 err.emit()
2228}
2229
2230pub(super) fn check_coroutine_obligations(
2231 tcx: TyCtxt<'_>,
2232 def_id: LocalDefId,
2233) -> Result<(), ErrorGuaranteed> {
2234 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()));
2235
2236 let typeck_results = tcx.typeck(def_id);
2237 let param_env = tcx.param_env(def_id);
2238
2239 {
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:2239",
"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(2239u32),
::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);
2240
2241 let mode = if tcx.next_trait_solver_globally() {
2242 TypingMode::borrowck(tcx, def_id)
2246 } else {
2247 TypingMode::analysis_in_body(tcx, def_id)
2248 };
2249
2250 let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2255
2256 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2257 for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2258 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2259 }
2260
2261 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2262 {
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:2262",
"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(2262u32),
::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);
2263 if !errors.is_empty() {
2264 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2265 }
2266
2267 if !tcx.next_trait_solver_globally() {
2268 for (key, ty) in infcx.take_opaque_types() {
2271 let hidden_type = infcx.resolve_vars_if_possible(ty);
2272 let key = infcx.resolve_vars_if_possible(key);
2273 sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2274 }
2275 } else {
2276 let _ = infcx.take_opaque_types();
2279 }
2280
2281 Ok(())
2282}
2283
2284pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2285 tcx: TyCtxt<'tcx>,
2286 def_id: LocalDefId,
2287) -> Result<(), ErrorGuaranteed> {
2288 if !tcx.next_trait_solver_globally() {
2289 return Ok(());
2290 }
2291 let typeck_results = tcx.typeck(def_id);
2292 let param_env = tcx.param_env(def_id);
2293
2294 let typing_mode = TypingMode::borrowck(tcx, def_id);
2296 let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2297 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2298 for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2299 let predicate = fold_regions(tcx, *predicate, |_, _| {
2300 infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2301 });
2302 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2303 }
2304
2305 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2306 {
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:2306",
"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(2306u32),
::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);
2307 if errors.is_empty() { Ok(()) } else { Err(infcx.err_ctxt().report_fulfillment_errors(errors)) }
2308}