1use std::cell::LazyCell;
2use std::ops::ControlFlow;
3
4use rustc_abi::FieldIdx;
5use rustc_attr_parsing::AttributeKind;
6use rustc_attr_parsing::ReprAttr::ReprPacked;
7use rustc_data_structures::unord::{UnordMap, UnordSet};
8use rustc_errors::MultiSpan;
9use rustc_errors::codes::*;
10use rustc_hir::def::{CtorKind, DefKind};
11use rustc_hir::{LangItem, Node, intravisit};
12use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
13use rustc_infer::traits::{Obligation, ObligationCauseCode};
14use rustc_lint_defs::builtin::{
15 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS, UNSUPPORTED_FN_PTR_CALLING_CONVENTIONS,
16};
17use rustc_middle::hir::nested_filter;
18use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
19use rustc_middle::middle::stability::EvalResult;
20use rustc_middle::ty::error::TypeErrorToStringExt;
21use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
22use rustc_middle::ty::util::{Discr, IntTypeExt};
23use rustc_middle::ty::{
24 AdtDef, BottomUpFolder, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,
25 TypeVisitable, TypeVisitableExt, fold_regions,
26};
27use rustc_session::lint::builtin::UNINHABITED_STATIC;
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;
34use {rustc_attr_parsing as attr, rustc_hir as hir};
35
36use super::compare_impl_item::check_type_bounds;
37use super::*;
38
39pub fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: ExternAbi) {
40 if !tcx.sess.target.is_abi_supported(abi) {
41 struct_span_code_err!(
42 tcx.dcx(),
43 span,
44 E0570,
45 "`{abi}` is not a supported ABI for the current target",
46 )
47 .emit();
48 }
49}
50
51pub fn check_abi_fn_ptr(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: ExternAbi) {
52 if !tcx.sess.target.is_abi_supported(abi) {
53 tcx.node_span_lint(UNSUPPORTED_FN_PTR_CALLING_CONVENTIONS, hir_id, span, |lint| {
54 lint.primary_message(format!(
55 "the calling convention {abi} is not supported on this target"
56 ));
57 });
58 }
59}
60
61fn check_struct(tcx: TyCtxt<'_>, def_id: LocalDefId) {
62 let def = tcx.adt_def(def_id);
63 let span = tcx.def_span(def_id);
64 def.destructor(tcx); if def.repr().simd() {
67 check_simd(tcx, span, def_id);
68 }
69
70 check_transparent(tcx, def);
71 check_packed(tcx, span, def);
72}
73
74fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
75 let def = tcx.adt_def(def_id);
76 let span = tcx.def_span(def_id);
77 def.destructor(tcx); check_transparent(tcx, def);
79 check_union_fields(tcx, span, def_id);
80 check_packed(tcx, span, def);
81}
82
83fn allowed_union_or_unsafe_field<'tcx>(
84 tcx: TyCtxt<'tcx>,
85 ty: Ty<'tcx>,
86 typing_env: ty::TypingEnv<'tcx>,
87 span: Span,
88) -> bool {
89 if ty.is_trivially_pure_clone_copy() {
94 return true;
95 }
96 let def_id = tcx
99 .lang_items()
100 .get(LangItem::BikeshedGuaranteedNoDrop)
101 .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, Some(span)));
102 let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, ty) else {
103 tcx.dcx().span_delayed_bug(span, "could not normalize field type");
104 return true;
105 };
106 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
107 infcx.predicate_must_hold_modulo_regions(&Obligation::new(
108 tcx,
109 ObligationCause::dummy_with_span(span),
110 param_env,
111 ty::TraitRef::new(tcx, def_id, [ty]),
112 ))
113}
114
115fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
117 let def = tcx.adt_def(item_def_id);
118 assert!(def.is_union());
119
120 let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
121 let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
122
123 for field in &def.non_enum_variant().fields {
124 if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
125 let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
126 Some(Node::Field(field)) => (field.span, field.ty.span),
128 _ => unreachable!("mir field has to correspond to hir field"),
129 };
130 tcx.dcx().emit_err(errors::InvalidUnionField {
131 field_span,
132 sugg: errors::InvalidUnionFieldSuggestion {
133 lo: ty_span.shrink_to_lo(),
134 hi: ty_span.shrink_to_hi(),
135 },
136 note: (),
137 });
138 return false;
139 }
140 }
141
142 true
143}
144
145fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
147 let ty = tcx.type_of(def_id).instantiate_identity();
153 let span = tcx.def_span(def_id);
154 let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
155 Ok(l) => l,
156 Err(LayoutError::SizeOverflow(_))
158 if matches!(tcx.def_kind(def_id), DefKind::Static{ .. }
159 if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
160 {
161 tcx.dcx().emit_err(errors::TooLargeStatic { span });
162 return;
163 }
164 Err(e) => {
166 tcx.dcx().span_delayed_bug(span, format!("{e:?}"));
167 return;
168 }
169 };
170 if layout.is_uninhabited() {
171 tcx.node_span_lint(
172 UNINHABITED_STATIC,
173 tcx.local_def_id_to_hir_id(def_id),
174 span,
175 |lint| {
176 lint.primary_message("static of uninhabited type");
177 lint
178 .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
179 },
180 );
181 }
182}
183
184fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
187 let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
188
189 if tcx.sess.opts.actually_rustdoc {
194 return;
195 }
196
197 if tcx.type_of(def_id).instantiate_identity().references_error() {
198 return;
199 }
200 if check_opaque_for_cycles(tcx, def_id).is_err() {
201 return;
202 }
203
204 let _ = check_opaque_meets_bounds(tcx, def_id, origin);
205}
206
207pub(super) fn check_opaque_for_cycles<'tcx>(
209 tcx: TyCtxt<'tcx>,
210 def_id: LocalDefId,
211) -> Result<(), ErrorGuaranteed> {
212 let args = GenericArgs::identity_for_item(tcx, def_id);
213
214 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
217 let reported = opaque_type_cycle_error(tcx, def_id);
218 return Err(reported);
219 }
220
221 Ok(())
222}
223
224#[instrument(level = "debug", skip(tcx))]
240fn check_opaque_meets_bounds<'tcx>(
241 tcx: TyCtxt<'tcx>,
242 def_id: LocalDefId,
243 origin: hir::OpaqueTyOrigin<LocalDefId>,
244) -> Result<(), ErrorGuaranteed> {
245 let (span, definition_def_id) =
246 if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
247 (span, Some(def_id))
248 } else {
249 (tcx.def_span(def_id), None)
250 };
251
252 let defining_use_anchor = match origin {
253 hir::OpaqueTyOrigin::FnReturn { parent, .. }
254 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
255 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
256 };
257 let param_env = tcx.param_env(defining_use_anchor);
258
259 let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
261 TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
262 } else {
263 TypingMode::analysis_in_body(tcx, defining_use_anchor)
264 });
265 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
266
267 let args = match origin {
268 hir::OpaqueTyOrigin::FnReturn { parent, .. }
269 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
270 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
271 tcx, parent,
272 )
273 .extend_to(tcx, def_id.to_def_id(), |param, _| {
274 tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
275 }),
276 };
277
278 let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
279
280 let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
287 let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
288 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)),
289 _ => re,
290 });
291
292 for (predicate, pred_span) in
296 tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx, args)
297 {
298 let predicate = predicate.fold_with(&mut BottomUpFolder {
299 tcx,
300 ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
301 lt_op: |lt| lt,
302 ct_op: |ct| ct,
303 });
304
305 ocx.register_obligation(Obligation::new(
306 tcx,
307 ObligationCause::new(
308 span,
309 def_id,
310 ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
311 ),
312 param_env,
313 predicate,
314 ));
315 }
316
317 let misc_cause = ObligationCause::misc(span, def_id);
318 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
322 Ok(()) => {}
323 Err(ty_err) => {
324 let ty_err = ty_err.to_string(tcx);
330 let guar = tcx.dcx().span_delayed_bug(
331 span,
332 format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
333 );
334 return Err(guar);
335 }
336 }
337
338 let predicate =
342 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
343 ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
344
345 let errors = ocx.select_all_or_error();
348 if !errors.is_empty() {
349 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
350 return Err(guar);
351 }
352
353 let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
354 ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
355
356 if infcx.next_trait_solver() {
357 Ok(())
358 } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
359 origin
360 {
361 let _ = infcx.take_opaque_types();
367 Ok(())
368 } else {
369 for (mut key, mut ty) in infcx.take_opaque_types() {
371 ty.ty = infcx.resolve_vars_if_possible(ty.ty);
372 key = infcx.resolve_vars_if_possible(key);
373 sanity_check_found_hidden_type(tcx, key, ty)?;
374 }
375 Ok(())
376 }
377}
378
379fn best_definition_site_of_opaque<'tcx>(
380 tcx: TyCtxt<'tcx>,
381 opaque_def_id: LocalDefId,
382 origin: hir::OpaqueTyOrigin<LocalDefId>,
383) -> Option<(Span, LocalDefId)> {
384 struct TaitConstraintLocator<'tcx> {
385 opaque_def_id: LocalDefId,
386 tcx: TyCtxt<'tcx>,
387 }
388 impl<'tcx> TaitConstraintLocator<'tcx> {
389 fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
390 if !self.tcx.has_typeck_results(item_def_id) {
391 return ControlFlow::Continue(());
392 }
393
394 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
395 if !opaque_types_defined_by.contains(&self.opaque_def_id) {
397 return ControlFlow::Continue(());
398 }
399
400 if let Some(hidden_ty) = self
401 .tcx
402 .mir_borrowck(item_def_id)
403 .ok()
404 .and_then(|opaque_types| opaque_types.0.get(&self.opaque_def_id))
405 {
406 ControlFlow::Break((hidden_ty.span, item_def_id))
407 } else {
408 ControlFlow::Continue(())
409 }
410 }
411 }
412 impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
413 type NestedFilter = nested_filter::All;
414 type Result = ControlFlow<(Span, LocalDefId)>;
415 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
416 self.tcx
417 }
418 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
419 intravisit::walk_expr(self, ex)
420 }
421 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
422 self.check(it.owner_id.def_id)?;
423 intravisit::walk_item(self, it)
424 }
425 fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
426 self.check(it.owner_id.def_id)?;
427 intravisit::walk_impl_item(self, it)
428 }
429 fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
430 self.check(it.owner_id.def_id)?;
431 intravisit::walk_trait_item(self, it)
432 }
433 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
434 intravisit::walk_foreign_item(self, it)
435 }
436 }
437
438 let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
439 match origin {
440 hir::OpaqueTyOrigin::FnReturn { parent, .. }
441 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
442 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
443 let impl_def_id = tcx.local_parent(parent);
444 for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
445 match assoc.kind {
446 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
447 if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
448 {
449 return Some(span);
450 }
451 }
452 ty::AssocKind::Type { .. } => {}
453 }
454 }
455
456 None
457 }
458 hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
459 tcx.hir_walk_toplevel_module(&mut locator).break_value()
460 }
461 }
462}
463
464fn sanity_check_found_hidden_type<'tcx>(
465 tcx: TyCtxt<'tcx>,
466 key: ty::OpaqueTypeKey<'tcx>,
467 mut ty: ty::OpaqueHiddenType<'tcx>,
468) -> Result<(), ErrorGuaranteed> {
469 if ty.ty.is_ty_var() {
470 return Ok(());
472 }
473 if let ty::Alias(ty::Opaque, alias) = ty.ty.kind() {
474 if alias.def_id == key.def_id.to_def_id() && alias.args == key.args {
475 return Ok(());
478 }
479 }
480 let strip_vars = |ty: Ty<'tcx>| {
481 ty.fold_with(&mut BottomUpFolder {
482 tcx,
483 ty_op: |t| t,
484 ct_op: |c| c,
485 lt_op: |l| match l.kind() {
486 RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
487 _ => l,
488 },
489 })
490 };
491 ty.ty = strip_vars(ty.ty);
494 let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args);
496 let hidden_ty = strip_vars(hidden_ty);
497
498 if hidden_ty == ty.ty {
500 Ok(())
501 } else {
502 let span = tcx.def_span(key.def_id);
503 let other = ty::OpaqueHiddenType { ty: hidden_ty, span };
504 Err(ty.build_mismatch_error(&other, tcx)?.emit())
505 }
506}
507
508fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
517 let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
518 let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
519 hir::GenericBound::Use(bounds, ..) => Some(bounds),
520 _ => None,
521 }) else {
522 return;
524 };
525
526 let mut expected_captures = UnordSet::default();
527 let mut shadowed_captures = UnordSet::default();
528 let mut seen_params = UnordMap::default();
529 let mut prev_non_lifetime_param = None;
530 for arg in precise_capturing_args {
531 let (hir_id, ident) = match *arg {
532 hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
533 hir_id,
534 ident,
535 ..
536 }) => {
537 if prev_non_lifetime_param.is_none() {
538 prev_non_lifetime_param = Some(ident);
539 }
540 (hir_id, ident)
541 }
542 hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
543 if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
544 tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
545 lifetime_span: ident.span,
546 name: ident.name,
547 other_span: prev_non_lifetime_param.span,
548 });
549 }
550 (hir_id, ident)
551 }
552 };
553
554 let ident = ident.normalize_to_macros_2_0();
555 if let Some(span) = seen_params.insert(ident, ident.span) {
556 tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
557 name: ident.name,
558 first_span: span,
559 second_span: ident.span,
560 });
561 }
562
563 match tcx.named_bound_var(hir_id) {
564 Some(ResolvedArg::EarlyBound(def_id)) => {
565 expected_captures.insert(def_id.to_def_id());
566
567 if let DefKind::LifetimeParam = tcx.def_kind(def_id)
573 && let Some(def_id) = tcx
574 .map_opaque_lifetime_to_parent_lifetime(def_id)
575 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
576 {
577 shadowed_captures.insert(def_id);
578 }
579 }
580 _ => {
581 tcx.dcx()
582 .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
583 }
584 }
585 }
586
587 let variances = tcx.variances_of(opaque_def_id);
588 let mut def_id = Some(opaque_def_id.to_def_id());
589 while let Some(generics) = def_id {
590 let generics = tcx.generics_of(generics);
591 def_id = generics.parent;
592
593 for param in &generics.own_params {
594 if expected_captures.contains(¶m.def_id) {
595 assert_eq!(
596 variances[param.index as usize],
597 ty::Invariant,
598 "precise captured param should be invariant"
599 );
600 continue;
601 }
602 if shadowed_captures.contains(¶m.def_id) {
606 continue;
607 }
608
609 match param.kind {
610 ty::GenericParamDefKind::Lifetime => {
611 let use_span = tcx.def_span(param.def_id);
612 let opaque_span = tcx.def_span(opaque_def_id);
613 if variances[param.index as usize] == ty::Invariant {
615 if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
616 && let Some(def_id) = tcx
617 .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
618 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
619 {
620 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
621 opaque_span,
622 use_span,
623 param_span: tcx.def_span(def_id),
624 });
625 } else {
626 if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
627 tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
628 opaque_span,
629 param_span: tcx.def_span(param.def_id),
630 });
631 } else {
632 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
637 opaque_span,
638 use_span: opaque_span,
639 param_span: use_span,
640 });
641 }
642 }
643 continue;
644 }
645 }
646 ty::GenericParamDefKind::Type { .. } => {
647 if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {
648 tcx.dcx().emit_err(errors::SelfTyNotCaptured {
650 trait_span: tcx.def_span(param.def_id),
651 opaque_span: tcx.def_span(opaque_def_id),
652 });
653 } else {
654 tcx.dcx().emit_err(errors::ParamNotCaptured {
656 param_span: tcx.def_span(param.def_id),
657 opaque_span: tcx.def_span(opaque_def_id),
658 kind: "type",
659 });
660 }
661 }
662 ty::GenericParamDefKind::Const { .. } => {
663 tcx.dcx().emit_err(errors::ParamNotCaptured {
665 param_span: tcx.def_span(param.def_id),
666 opaque_span: tcx.def_span(opaque_def_id),
667 kind: "const",
668 });
669 }
670 }
671 }
672 }
673}
674
675fn is_enum_of_nonnullable_ptr<'tcx>(
676 tcx: TyCtxt<'tcx>,
677 adt_def: AdtDef<'tcx>,
678 args: GenericArgsRef<'tcx>,
679) -> bool {
680 if adt_def.repr().inhibit_enum_layout_opt() {
681 return false;
682 }
683
684 let [var_one, var_two] = &adt_def.variants().raw[..] else {
685 return false;
686 };
687 let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
688 return false;
689 };
690 matches!(field.ty(tcx, args).kind(), ty::FnPtr(..) | ty::Ref(..))
691}
692
693fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
694 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
695 if match tcx.type_of(def_id).instantiate_identity().kind() {
696 ty::RawPtr(_, _) => false,
697 ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
698 _ => true,
699 } {
700 tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
701 }
702 }
703}
704
705pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) {
706 match tcx.def_kind(def_id) {
707 DefKind::Static { .. } => {
708 check_static_inhabited(tcx, def_id);
709 check_static_linkage(tcx, def_id);
710 }
711 DefKind::Const => {}
712 DefKind::Enum => {
713 check_enum(tcx, def_id);
714 }
715 DefKind::Fn => {
716 if let Some(i) = tcx.intrinsic(def_id) {
717 intrinsic::check_intrinsic_type(
718 tcx,
719 def_id,
720 tcx.def_ident_span(def_id).unwrap(),
721 i.name,
722 )
723 }
724 }
725 DefKind::Impl { of_trait } => {
726 if of_trait && let Some(impl_trait_header) = tcx.impl_trait_header(def_id) {
727 if tcx
728 .ensure_ok()
729 .coherent_trait(impl_trait_header.trait_ref.instantiate_identity().def_id)
730 .is_ok()
731 {
732 check_impl_items_against_trait(tcx, def_id, impl_trait_header);
733 }
734 }
735 }
736 DefKind::Trait => {
737 let assoc_items = tcx.associated_items(def_id);
738 check_on_unimplemented(tcx, def_id);
739
740 for &assoc_item in assoc_items.in_definition_order() {
741 match assoc_item.kind {
742 ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
743 let trait_args = GenericArgs::identity_for_item(tcx, def_id);
744 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
745 tcx,
746 assoc_item,
747 assoc_item,
748 ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
749 );
750 }
751 _ => {}
752 }
753 }
754 }
755 DefKind::Struct => {
756 check_struct(tcx, def_id);
757 }
758 DefKind::Union => {
759 check_union(tcx, def_id);
760 }
761 DefKind::OpaqueTy => {
762 check_opaque_precise_captures(tcx, def_id);
763
764 let origin = tcx.local_opaque_ty_origin(def_id);
765 if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
766 | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
767 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
768 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
769 {
770 } else {
772 check_opaque(tcx, def_id);
773 }
774 }
775 DefKind::TyAlias => {
776 check_type_alias_type_params_are_used(tcx, def_id);
777 }
778 DefKind::ForeignMod => {
779 let it = tcx.hir_expect_item(def_id);
780 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
781 return;
782 };
783 check_abi(tcx, it.span, abi);
784
785 for item in items {
786 let def_id = item.id.owner_id.def_id;
787
788 let generics = tcx.generics_of(def_id);
789 let own_counts = generics.own_counts();
790 if generics.own_params.len() - own_counts.lifetimes != 0 {
791 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
792 (_, 0) => ("type", "types", Some("u32")),
793 (0, _) => ("const", "consts", None),
796 _ => ("type or const", "types or consts", None),
797 };
798 struct_span_code_err!(
799 tcx.dcx(),
800 item.span,
801 E0044,
802 "foreign items may not have {kinds} parameters",
803 )
804 .with_span_label(item.span, format!("can't have {kinds} parameters"))
805 .with_help(
806 format!(
809 "replace the {} parameters with concrete {}{}",
810 kinds,
811 kinds_pl,
812 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
813 ),
814 )
815 .emit();
816 }
817
818 let item = tcx.hir_foreign_item(item.id);
819 match &item.kind {
820 hir::ForeignItemKind::Fn(sig, _, _) => {
821 require_c_abi_if_c_variadic(tcx, sig.decl, abi, item.span);
822 }
823 hir::ForeignItemKind::Static(..) => {
824 check_static_inhabited(tcx, def_id);
825 check_static_linkage(tcx, def_id);
826 }
827 _ => {}
828 }
829 }
830 }
831 _ => {}
832 }
833}
834
835pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, def_id: LocalDefId) {
836 let _ = OnUnimplementedDirective::of_item(tcx, def_id.to_def_id());
838}
839
840pub(super) fn check_specialization_validity<'tcx>(
841 tcx: TyCtxt<'tcx>,
842 trait_def: &ty::TraitDef,
843 trait_item: ty::AssocItem,
844 impl_id: DefId,
845 impl_item: DefId,
846) {
847 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
848 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
849 if parent.is_from_trait() {
850 None
851 } else {
852 Some((parent, parent.item(tcx, trait_item.def_id)))
853 }
854 });
855
856 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
857 match parent_item {
858 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
861 Some(Err(parent_impl.def_id()))
862 }
863
864 Some(_) => Some(Ok(())),
866
867 None => {
871 if tcx.defaultness(parent_impl.def_id()).is_default() {
872 None
873 } else {
874 Some(Err(parent_impl.def_id()))
875 }
876 }
877 }
878 });
879
880 let result = opt_result.unwrap_or(Ok(()));
883
884 if let Err(parent_impl) = result {
885 if !tcx.is_impl_trait_in_trait(impl_item) {
886 report_forbidden_specialization(tcx, impl_item, parent_impl);
887 } else {
888 tcx.dcx().delayed_bug(format!("parent item: {parent_impl:?} not marked as default"));
889 }
890 }
891}
892
893fn check_impl_items_against_trait<'tcx>(
894 tcx: TyCtxt<'tcx>,
895 impl_id: LocalDefId,
896 impl_trait_header: ty::ImplTraitHeader<'tcx>,
897) {
898 let trait_ref = impl_trait_header.trait_ref.instantiate_identity();
899 if trait_ref.references_error() {
903 return;
904 }
905
906 let impl_item_refs = tcx.associated_item_def_ids(impl_id);
907
908 match impl_trait_header.polarity {
910 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
911 ty::ImplPolarity::Negative => {
912 if let [first_item_ref, ..] = impl_item_refs {
913 let first_item_span = tcx.def_span(first_item_ref);
914 struct_span_code_err!(
915 tcx.dcx(),
916 first_item_span,
917 E0749,
918 "negative impls cannot have any items"
919 )
920 .emit();
921 }
922 return;
923 }
924 }
925
926 let trait_def = tcx.trait_def(trait_ref.def_id);
927
928 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
929
930 for &impl_item in impl_item_refs {
931 let ty_impl_item = tcx.associated_item(impl_item);
932 let ty_trait_item = if let Some(trait_item_id) = ty_impl_item.trait_item_def_id {
933 tcx.associated_item(trait_item_id)
934 } else {
935 tcx.dcx().span_delayed_bug(tcx.def_span(impl_item), "missing associated item in trait");
937 continue;
938 };
939
940 let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
941
942 if res.is_ok() {
943 match ty_impl_item.kind {
944 ty::AssocKind::Fn { .. } => {
945 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
946 tcx,
947 ty_impl_item,
948 ty_trait_item,
949 tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
950 .unwrap()
951 .instantiate_identity(),
952 );
953 }
954 ty::AssocKind::Const { .. } => {}
955 ty::AssocKind::Type { .. } => {}
956 }
957 }
958
959 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
960 tcx.emit_node_span_lint(
961 rustc_lint_defs::builtin::DEAD_CODE,
962 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
963 tcx.def_span(ty_impl_item.def_id),
964 errors::UselessImplItem,
965 )
966 }
967
968 check_specialization_validity(
969 tcx,
970 trait_def,
971 ty_trait_item,
972 impl_id.to_def_id(),
973 impl_item,
974 );
975 }
976
977 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
978 let mut missing_items = Vec::new();
980
981 let mut must_implement_one_of: Option<&[Ident]> =
982 trait_def.must_implement_one_of.as_deref();
983
984 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
985 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
986
987 let is_implemented = leaf_def
988 .as_ref()
989 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
990
991 if !is_implemented
992 && tcx.defaultness(impl_id).is_final()
993 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
995 {
996 missing_items.push(tcx.associated_item(trait_item_id));
997 }
998
999 let is_implemented_here =
1001 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1002
1003 if !is_implemented_here {
1004 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1005 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1006 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1007 tcx,
1008 full_impl_span,
1009 trait_item_id,
1010 feature,
1011 reason,
1012 issue,
1013 ),
1014
1015 EvalResult::Allow | EvalResult::Unmarked => {}
1017 }
1018 }
1019
1020 if let Some(required_items) = &must_implement_one_of {
1021 if is_implemented_here {
1022 let trait_item = tcx.associated_item(trait_item_id);
1023 if required_items.contains(&trait_item.ident(tcx)) {
1024 must_implement_one_of = None;
1025 }
1026 }
1027 }
1028
1029 if let Some(leaf_def) = &leaf_def
1030 && !leaf_def.is_final()
1031 && let def_id = leaf_def.item.def_id
1032 && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1033 {
1034 let def_kind = tcx.def_kind(def_id);
1035 let descr = tcx.def_kind_descr(def_kind, def_id);
1036 let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1037 (
1038 format!("async {descr} in trait cannot be specialized"),
1039 "async functions in traits",
1040 )
1041 } else {
1042 (
1043 format!(
1044 "{descr} with return-position `impl Trait` in trait cannot be specialized"
1045 ),
1046 "return position `impl Trait` in traits",
1047 )
1048 };
1049 tcx.dcx()
1050 .struct_span_err(tcx.def_span(def_id), msg)
1051 .with_note(format!(
1052 "specialization behaves in inconsistent and surprising ways with \
1053 {feature}, and for now is disallowed"
1054 ))
1055 .emit();
1056 }
1057 }
1058
1059 if !missing_items.is_empty() {
1060 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1061 missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1062 }
1063
1064 if let Some(missing_items) = must_implement_one_of {
1065 let attr_span = tcx
1066 .get_attr(trait_ref.def_id, sym::rustc_must_implement_one_of)
1067 .map(|attr| attr.span());
1068
1069 missing_items_must_implement_one_of_err(
1070 tcx,
1071 tcx.def_span(impl_id),
1072 missing_items,
1073 attr_span,
1074 );
1075 }
1076 }
1077}
1078
1079fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1080 let t = tcx.type_of(def_id).instantiate_identity();
1081 if let ty::Adt(def, args) = t.kind()
1082 && def.is_struct()
1083 {
1084 let fields = &def.non_enum_variant().fields;
1085 if fields.is_empty() {
1086 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1087 return;
1088 }
1089
1090 let array_field = &fields[FieldIdx::ZERO];
1091 let array_ty = array_field.ty(tcx, args);
1092 let ty::Array(element_ty, len_const) = array_ty.kind() else {
1093 struct_span_code_err!(
1094 tcx.dcx(),
1095 sp,
1096 E0076,
1097 "SIMD vector's only field must be an array"
1098 )
1099 .with_span_label(tcx.def_span(array_field.did), "not an array")
1100 .emit();
1101 return;
1102 };
1103
1104 if let Some(second_field) = fields.get(FieldIdx::from_u32(1)) {
1105 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1106 .with_span_label(tcx.def_span(second_field.did), "excess field")
1107 .emit();
1108 return;
1109 }
1110
1111 if let Some(len) = len_const.try_to_target_usize(tcx) {
1116 if len == 0 {
1117 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1118 return;
1119 } else if len > MAX_SIMD_LANES {
1120 struct_span_code_err!(
1121 tcx.dcx(),
1122 sp,
1123 E0075,
1124 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1125 )
1126 .emit();
1127 return;
1128 }
1129 }
1130
1131 match element_ty.kind() {
1136 ty::Param(_) => (), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), _ => {
1139 struct_span_code_err!(
1140 tcx.dcx(),
1141 sp,
1142 E0077,
1143 "SIMD vector element type should be a \
1144 primitive scalar (integer/float/pointer) type"
1145 )
1146 .emit();
1147 return;
1148 }
1149 }
1150 }
1151}
1152
1153pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1154 let repr = def.repr();
1155 if repr.packed() {
1156 if let Some(reprs) =
1157 attr::find_attr!(tcx.get_all_attrs(def.did()), AttributeKind::Repr(r) => r)
1158 {
1159 for (r, _) in reprs {
1160 if let ReprPacked(pack) = r
1161 && let Some(repr_pack) = repr.pack
1162 && pack != &repr_pack
1163 {
1164 struct_span_code_err!(
1165 tcx.dcx(),
1166 sp,
1167 E0634,
1168 "type has conflicting packed representation hints"
1169 )
1170 .emit();
1171 }
1172 }
1173 }
1174 if repr.align.is_some() {
1175 struct_span_code_err!(
1176 tcx.dcx(),
1177 sp,
1178 E0587,
1179 "type has conflicting packed and align representation hints"
1180 )
1181 .emit();
1182 } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1183 let mut err = struct_span_code_err!(
1184 tcx.dcx(),
1185 sp,
1186 E0588,
1187 "packed type cannot transitively contain a `#[repr(align)]` type"
1188 );
1189
1190 err.span_note(
1191 tcx.def_span(def_spans[0].0),
1192 format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
1193 );
1194
1195 if def_spans.len() > 2 {
1196 let mut first = true;
1197 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1198 let ident = tcx.item_name(*adt_def);
1199 err.span_note(
1200 *span,
1201 if first {
1202 format!(
1203 "`{}` contains a field of type `{}`",
1204 tcx.type_of(def.did()).instantiate_identity(),
1205 ident
1206 )
1207 } else {
1208 format!("...which contains a field of type `{ident}`")
1209 },
1210 );
1211 first = false;
1212 }
1213 }
1214
1215 err.emit();
1216 }
1217 }
1218}
1219
1220pub(super) fn check_packed_inner(
1221 tcx: TyCtxt<'_>,
1222 def_id: DefId,
1223 stack: &mut Vec<DefId>,
1224) -> Option<Vec<(DefId, Span)>> {
1225 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1226 if def.is_struct() || def.is_union() {
1227 if def.repr().align.is_some() {
1228 return Some(vec![(def.did(), DUMMY_SP)]);
1229 }
1230
1231 stack.push(def_id);
1232 for field in &def.non_enum_variant().fields {
1233 if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1234 && !stack.contains(&def.did())
1235 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1236 {
1237 defs.push((def.did(), field.ident(tcx).span));
1238 return Some(defs);
1239 }
1240 }
1241 stack.pop();
1242 }
1243 }
1244
1245 None
1246}
1247
1248pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1249 if !adt.repr().transparent() {
1250 return;
1251 }
1252
1253 if adt.is_union() && !tcx.features().transparent_unions() {
1254 feature_err(
1255 &tcx.sess,
1256 sym::transparent_unions,
1257 tcx.def_span(adt.did()),
1258 "transparent unions are unstable",
1259 )
1260 .emit();
1261 }
1262
1263 if adt.variants().len() != 1 {
1264 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1265 return;
1267 }
1268
1269 let field_infos = adt.all_fields().map(|field| {
1272 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1273 let typing_env = ty::TypingEnv::non_body_analysis(tcx, field.did);
1274 let layout = tcx.layout_of(typing_env.as_query_input(ty));
1275 let span = tcx.hir_span_if_local(field.did).unwrap();
1277 let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1278 if !trivial {
1279 return (span, trivial, None);
1280 }
1281 fn check_non_exhaustive<'tcx>(
1284 tcx: TyCtxt<'tcx>,
1285 t: Ty<'tcx>,
1286 ) -> ControlFlow<(&'static str, DefId, GenericArgsRef<'tcx>, bool)> {
1287 match t.kind() {
1288 ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1289 ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1290 ty::Adt(def, args) => {
1291 if !def.did().is_local() && !tcx.has_attr(def.did(), sym::rustc_pub_transparent)
1292 {
1293 let non_exhaustive = def.is_variant_list_non_exhaustive()
1294 || def
1295 .variants()
1296 .iter()
1297 .any(ty::VariantDef::is_field_list_non_exhaustive);
1298 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1299 if non_exhaustive || has_priv {
1300 return ControlFlow::Break((
1301 def.descr(),
1302 def.did(),
1303 args,
1304 non_exhaustive,
1305 ));
1306 }
1307 }
1308 def.all_fields()
1309 .map(|field| field.ty(tcx, args))
1310 .try_for_each(|t| check_non_exhaustive(tcx, t))
1311 }
1312 _ => ControlFlow::Continue(()),
1313 }
1314 }
1315
1316 (span, trivial, check_non_exhaustive(tcx, ty).break_value())
1317 });
1318
1319 let non_trivial_fields = field_infos
1320 .clone()
1321 .filter_map(|(span, trivial, _non_exhaustive)| if !trivial { Some(span) } else { None });
1322 let non_trivial_count = non_trivial_fields.clone().count();
1323 if non_trivial_count >= 2 {
1324 bad_non_zero_sized_fields(
1325 tcx,
1326 adt,
1327 non_trivial_count,
1328 non_trivial_fields,
1329 tcx.def_span(adt.did()),
1330 );
1331 return;
1332 }
1333 let mut prev_non_exhaustive_1zst = false;
1334 for (span, _trivial, non_exhaustive_1zst) in field_infos {
1335 if let Some((descr, def_id, args, non_exhaustive)) = non_exhaustive_1zst {
1336 if non_trivial_count > 0 || prev_non_exhaustive_1zst {
1339 tcx.node_span_lint(
1340 REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1341 tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1342 span,
1343 |lint| {
1344 lint.primary_message(
1345 "zero-sized fields in `repr(transparent)` cannot \
1346 contain external non-exhaustive types",
1347 );
1348 let note = if non_exhaustive {
1349 "is marked with `#[non_exhaustive]`"
1350 } else {
1351 "contains private fields"
1352 };
1353 let field_ty = tcx.def_path_str_with_args(def_id, args);
1354 lint.note(format!(
1355 "this {descr} contains `{field_ty}`, which {note}, \
1356 and makes it not a breaking change to become \
1357 non-zero-sized in the future."
1358 ));
1359 },
1360 )
1361 } else {
1362 prev_non_exhaustive_1zst = true;
1363 }
1364 }
1365 }
1366}
1367
1368#[allow(trivial_numeric_casts)]
1369fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1370 let def = tcx.adt_def(def_id);
1371 def.destructor(tcx); if def.variants().is_empty() {
1374 attr::find_attr!(
1375 tcx.get_all_attrs(def_id),
1376 AttributeKind::Repr(rs) => {
1377 struct_span_code_err!(
1378 tcx.dcx(),
1379 rs.first().unwrap().1,
1380 E0084,
1381 "unsupported representation for zero-variant enum"
1382 )
1383 .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1384 .emit();
1385 }
1386 );
1387 }
1388
1389 let repr_type_ty = def.repr().discr_type().to_ty(tcx);
1390 if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
1391 if !tcx.features().repr128() {
1392 feature_err(
1393 &tcx.sess,
1394 sym::repr128,
1395 tcx.def_span(def_id),
1396 "repr with 128-bit type is unstable",
1397 )
1398 .emit();
1399 }
1400 }
1401
1402 for v in def.variants() {
1403 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1404 tcx.ensure_ok().typeck(discr_def_id.expect_local());
1405 }
1406 }
1407
1408 if def.repr().int.is_none() {
1409 let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1410 let has_disr = |var: &ty::VariantDef| matches!(var.discr, ty::VariantDiscr::Explicit(_));
1411
1412 let has_non_units = def.variants().iter().any(|var| !is_unit(var));
1413 let disr_units = def.variants().iter().any(|var| is_unit(var) && has_disr(var));
1414 let disr_non_unit = def.variants().iter().any(|var| !is_unit(var) && has_disr(var));
1415
1416 if disr_non_unit || (disr_units && has_non_units) {
1417 struct_span_code_err!(
1418 tcx.dcx(),
1419 tcx.def_span(def_id),
1420 E0732,
1421 "`#[repr(inttype)]` must be specified"
1422 )
1423 .emit();
1424 }
1425 }
1426
1427 detect_discriminant_duplicate(tcx, def);
1428 check_transparent(tcx, def);
1429}
1430
1431fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1433 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1436 let var = adt.variant(idx); let (span, display_discr) = match var.discr {
1438 ty::VariantDiscr::Explicit(discr_def_id) => {
1439 if let hir::Node::AnonConst(expr) =
1441 tcx.hir_node_by_def_id(discr_def_id.expect_local())
1442 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1443 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1444 && *lit_value != dis.val
1445 {
1446 (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1447 } else {
1448 (tcx.def_span(discr_def_id), format!("`{dis}`"))
1450 }
1451 }
1452 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1454 ty::VariantDiscr::Relative(distance_to_explicit) => {
1455 if let Some(explicit_idx) =
1460 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1461 {
1462 let explicit_variant = adt.variant(explicit_idx);
1463 let ve_ident = var.name;
1464 let ex_ident = explicit_variant.name;
1465 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1466
1467 err.span_label(
1468 tcx.def_span(explicit_variant.def_id),
1469 format!(
1470 "discriminant for `{ve_ident}` incremented from this startpoint \
1471 (`{ex_ident}` + {distance_to_explicit} {sp} later \
1472 => `{ve_ident}` = {dis})"
1473 ),
1474 );
1475 }
1476
1477 (tcx.def_span(var.def_id), format!("`{dis}`"))
1478 }
1479 };
1480
1481 err.span_label(span, format!("{display_discr} assigned here"));
1482 };
1483
1484 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1485
1486 let mut i = 0;
1493 while i < discrs.len() {
1494 let var_i_idx = discrs[i].0;
1495 let mut error: Option<Diag<'_, _>> = None;
1496
1497 let mut o = i + 1;
1498 while o < discrs.len() {
1499 let var_o_idx = discrs[o].0;
1500
1501 if discrs[i].1.val == discrs[o].1.val {
1502 let err = error.get_or_insert_with(|| {
1503 let mut ret = struct_span_code_err!(
1504 tcx.dcx(),
1505 tcx.def_span(adt.did()),
1506 E0081,
1507 "discriminant value `{}` assigned more than once",
1508 discrs[i].1,
1509 );
1510
1511 report(discrs[i].1, var_i_idx, &mut ret);
1512
1513 ret
1514 });
1515
1516 report(discrs[o].1, var_o_idx, err);
1517
1518 discrs[o] = *discrs.last().unwrap();
1520 discrs.pop();
1521 } else {
1522 o += 1;
1523 }
1524 }
1525
1526 if let Some(e) = error {
1527 e.emit();
1528 }
1529
1530 i += 1;
1531 }
1532}
1533
1534fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1535 if tcx.type_alias_is_lazy(def_id) {
1536 return;
1539 }
1540
1541 let generics = tcx.generics_of(def_id);
1542 if generics.own_counts().types == 0 {
1543 return;
1544 }
1545
1546 let ty = tcx.type_of(def_id).instantiate_identity();
1547 if ty.references_error() {
1548 return;
1550 }
1551
1552 let bounded_params = LazyCell::new(|| {
1554 tcx.explicit_predicates_of(def_id)
1555 .predicates
1556 .iter()
1557 .filter_map(|(predicate, span)| {
1558 let bounded_ty = match predicate.kind().skip_binder() {
1559 ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1560 ty::ClauseKind::TypeOutlives(pred) => pred.0,
1561 _ => return None,
1562 };
1563 if let ty::Param(param) = bounded_ty.kind() {
1564 Some((param.index, span))
1565 } else {
1566 None
1567 }
1568 })
1569 .collect::<FxIndexMap<_, _>>()
1575 });
1576
1577 let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1578 for leaf in ty.walk() {
1579 if let GenericArgKind::Type(leaf_ty) = leaf.unpack()
1580 && let ty::Param(param) = leaf_ty.kind()
1581 {
1582 debug!("found use of ty param {:?}", param);
1583 params_used.insert(param.index);
1584 }
1585 }
1586
1587 for param in &generics.own_params {
1588 if !params_used.contains(param.index)
1589 && let ty::GenericParamDefKind::Type { .. } = param.kind
1590 {
1591 let span = tcx.def_span(param.def_id);
1592 let param_name = Ident::new(param.name, span);
1593
1594 let has_explicit_bounds = bounded_params.is_empty()
1598 || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span);
1599 let const_param_help = !has_explicit_bounds;
1600
1601 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
1602 span,
1603 param_name,
1604 param_def_kind: tcx.def_descr(param.def_id),
1605 help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
1606 usage_spans: vec![],
1607 const_param_help,
1608 });
1609 diag.code(E0091);
1610 diag.emit();
1611 }
1612 }
1613}
1614
1615fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
1624 let span = tcx.def_span(opaque_def_id);
1625 let mut err = struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
1626
1627 let mut label = false;
1628 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
1629 let typeck_results = tcx.typeck(def_id);
1630 if visitor
1631 .returns
1632 .iter()
1633 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1634 .all(|ty| matches!(ty.kind(), ty::Never))
1635 {
1636 let spans = visitor
1637 .returns
1638 .iter()
1639 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1640 .map(|expr| expr.span)
1641 .collect::<Vec<Span>>();
1642 let span_len = spans.len();
1643 if span_len == 1 {
1644 err.span_label(spans[0], "this returned value is of `!` type");
1645 } else {
1646 let mut multispan: MultiSpan = spans.clone().into();
1647 for span in spans {
1648 multispan.push_span_label(span, "this returned value is of `!` type");
1649 }
1650 err.span_note(multispan, "these returned values have a concrete \"never\" type");
1651 }
1652 err.help("this error will resolve once the item's body returns a concrete type");
1653 } else {
1654 let mut seen = FxHashSet::default();
1655 seen.insert(span);
1656 err.span_label(span, "recursive opaque type");
1657 label = true;
1658 for (sp, ty) in visitor
1659 .returns
1660 .iter()
1661 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1662 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1663 {
1664 #[derive(Default)]
1665 struct OpaqueTypeCollector {
1666 opaques: Vec<DefId>,
1667 closures: Vec<DefId>,
1668 }
1669 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
1670 fn visit_ty(&mut self, t: Ty<'tcx>) {
1671 match *t.kind() {
1672 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1673 self.opaques.push(def);
1674 }
1675 ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
1676 self.closures.push(def_id);
1677 t.super_visit_with(self);
1678 }
1679 _ => t.super_visit_with(self),
1680 }
1681 }
1682 }
1683
1684 let mut visitor = OpaqueTypeCollector::default();
1685 ty.visit_with(&mut visitor);
1686 for def_id in visitor.opaques {
1687 let ty_span = tcx.def_span(def_id);
1688 if !seen.contains(&ty_span) {
1689 let descr = if ty.is_impl_trait() { "opaque " } else { "" };
1690 err.span_label(ty_span, format!("returning this {descr}type `{ty}`"));
1691 seen.insert(ty_span);
1692 }
1693 err.span_label(sp, format!("returning here with type `{ty}`"));
1694 }
1695
1696 for closure_def_id in visitor.closures {
1697 let Some(closure_local_did) = closure_def_id.as_local() else {
1698 continue;
1699 };
1700 let typeck_results = tcx.typeck(closure_local_did);
1701
1702 let mut label_match = |ty: Ty<'_>, span| {
1703 for arg in ty.walk() {
1704 if let ty::GenericArgKind::Type(ty) = arg.unpack()
1705 && let ty::Alias(
1706 ty::Opaque,
1707 ty::AliasTy { def_id: captured_def_id, .. },
1708 ) = *ty.kind()
1709 && captured_def_id == opaque_def_id.to_def_id()
1710 {
1711 err.span_label(
1712 span,
1713 format!(
1714 "{} captures itself here",
1715 tcx.def_descr(closure_def_id)
1716 ),
1717 );
1718 }
1719 }
1720 };
1721
1722 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
1724 {
1725 label_match(capture.place.ty(), capture.get_path_span(tcx));
1726 }
1727 if tcx.is_coroutine(closure_def_id)
1729 && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
1730 {
1731 for interior_ty in &coroutine_layout.field_tys {
1732 label_match(interior_ty.ty, interior_ty.source_info.span);
1733 }
1734 }
1735 }
1736 }
1737 }
1738 }
1739 if !label {
1740 err.span_label(span, "cannot resolve opaque type");
1741 }
1742 err.emit()
1743}
1744
1745pub(super) fn check_coroutine_obligations(
1746 tcx: TyCtxt<'_>,
1747 def_id: LocalDefId,
1748) -> Result<(), ErrorGuaranteed> {
1749 debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
1750
1751 let typeck_results = tcx.typeck(def_id);
1752 let param_env = tcx.param_env(def_id);
1753
1754 debug!(?typeck_results.coroutine_stalled_predicates);
1755
1756 let mode = if tcx.next_trait_solver_globally() {
1757 TypingMode::post_borrowck_analysis(tcx, def_id)
1758 } else {
1759 TypingMode::analysis_in_body(tcx, def_id)
1760 };
1761
1762 let infcx = tcx
1763 .infer_ctxt()
1764 .ignoring_regions()
1767 .build(mode);
1768
1769 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1770 for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
1771 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
1772 }
1773
1774 let errors = ocx.select_all_or_error();
1775 debug!(?errors);
1776 if !errors.is_empty() {
1777 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
1778 }
1779
1780 if !tcx.next_trait_solver_globally() {
1781 for (key, ty) in infcx.take_opaque_types() {
1784 let hidden_type = infcx.resolve_vars_if_possible(ty);
1785 let key = infcx.resolve_vars_if_possible(key);
1786 sanity_check_found_hidden_type(tcx, key, hidden_type)?;
1787 }
1788 }
1789
1790 Ok(())
1791}