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