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::AttributeKind;
10use rustc_hir::attrs::ReprAttr::ReprPacked;
11use rustc_hir::def::{CtorKind, DefKind};
12use rustc_hir::{LangItem, Node, attrs, find_attr, intravisit};
13use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
14use rustc_infer::traits::{Obligation, ObligationCauseCode, WellFormedLoc};
15use rustc_lint_defs::builtin::{REPR_TRANSPARENT_NON_ZST_FIELDS, UNSUPPORTED_CALLING_CONVENTIONS};
16use rustc_middle::hir::nested_filter;
17use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
18use rustc_middle::middle::stability::EvalResult;
19use rustc_middle::ty::error::TypeErrorToStringExt;
20use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
21use rustc_middle::ty::util::Discr;
22use rustc_middle::ty::{
23 AdtDef, BottomUpFolder, FnSig, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable,
24 TypeVisitable, TypeVisitableExt, fold_regions,
25};
26use rustc_session::lint::builtin::UNINHABITED_STATIC;
27use rustc_target::spec::{AbiMap, AbiMapping};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::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(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(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, 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(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 !find_attr!(tcx.get_all_attrs(def_id), AttributeKind::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 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 _ => 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 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) => {
197 tcx.dcx().span_delayed_bug(span, format!("{e:?}"));
198 return;
199 }
200 };
201 if layout.is_uninhabited() {
202 tcx.node_span_lint(
203 UNINHABITED_STATIC,
204 tcx.local_def_id_to_hir_id(def_id),
205 span,
206 |lint| {
207 lint.primary_message("static of uninhabited type");
208 lint
209 .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
210 },
211 );
212 }
213}
214
215fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
218 let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
219
220 if tcx.sess.opts.actually_rustdoc {
225 return;
226 }
227
228 if tcx.type_of(def_id).instantiate_identity().references_error() {
229 return;
230 }
231 if check_opaque_for_cycles(tcx, def_id).is_err() {
232 return;
233 }
234
235 let _ = check_opaque_meets_bounds(tcx, def_id, origin);
236}
237
238pub(super) fn check_opaque_for_cycles<'tcx>(
240 tcx: TyCtxt<'tcx>,
241 def_id: LocalDefId,
242) -> Result<(), ErrorGuaranteed> {
243 let args = GenericArgs::identity_for_item(tcx, def_id);
244
245 if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
248 let reported = opaque_type_cycle_error(tcx, def_id);
249 return Err(reported);
250 }
251
252 Ok(())
253}
254
255#[instrument(level = "debug", skip(tcx))]
271fn check_opaque_meets_bounds<'tcx>(
272 tcx: TyCtxt<'tcx>,
273 def_id: LocalDefId,
274 origin: hir::OpaqueTyOrigin<LocalDefId>,
275) -> Result<(), ErrorGuaranteed> {
276 let (span, definition_def_id) =
277 if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
278 (span, Some(def_id))
279 } else {
280 (tcx.def_span(def_id), None)
281 };
282
283 let defining_use_anchor = match origin {
284 hir::OpaqueTyOrigin::FnReturn { parent, .. }
285 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
286 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
287 };
288 let param_env = tcx.param_env(defining_use_anchor);
289
290 let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
292 TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
293 } else {
294 TypingMode::analysis_in_body(tcx, defining_use_anchor)
295 });
296 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
297
298 let args = match origin {
299 hir::OpaqueTyOrigin::FnReturn { parent, .. }
300 | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
301 | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
302 tcx, parent,
303 )
304 .extend_to(tcx, def_id.to_def_id(), |param, _| {
305 tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
306 }),
307 };
308
309 let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
310
311 let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
318 let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
319 ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
320 _ => re,
321 });
322
323 for (predicate, pred_span) in
327 tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx, args)
328 {
329 let predicate = predicate.fold_with(&mut BottomUpFolder {
330 tcx,
331 ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
332 lt_op: |lt| lt,
333 ct_op: |ct| ct,
334 });
335
336 ocx.register_obligation(Obligation::new(
337 tcx,
338 ObligationCause::new(
339 span,
340 def_id,
341 ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
342 ),
343 param_env,
344 predicate,
345 ));
346 }
347
348 let misc_cause = ObligationCause::misc(span, def_id);
349 match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
353 Ok(()) => {}
354 Err(ty_err) => {
355 let ty_err = ty_err.to_string(tcx);
361 let guar = tcx.dcx().span_delayed_bug(
362 span,
363 format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
364 );
365 return Err(guar);
366 }
367 }
368
369 let predicate =
373 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
374 ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
375
376 let errors = ocx.evaluate_obligations_error_on_ambiguity();
379 if !errors.is_empty() {
380 let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
381 return Err(guar);
382 }
383
384 let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
385 ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
386
387 if infcx.next_trait_solver() {
388 Ok(())
389 } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
390 origin
391 {
392 let _ = infcx.take_opaque_types();
398 Ok(())
399 } else {
400 for (mut key, mut ty) in infcx.take_opaque_types() {
402 ty.ty = infcx.resolve_vars_if_possible(ty.ty);
403 key = infcx.resolve_vars_if_possible(key);
404 sanity_check_found_hidden_type(tcx, key, ty)?;
405 }
406 Ok(())
407 }
408}
409
410fn best_definition_site_of_opaque<'tcx>(
411 tcx: TyCtxt<'tcx>,
412 opaque_def_id: LocalDefId,
413 origin: hir::OpaqueTyOrigin<LocalDefId>,
414) -> Option<(Span, LocalDefId)> {
415 struct TaitConstraintLocator<'tcx> {
416 opaque_def_id: LocalDefId,
417 tcx: TyCtxt<'tcx>,
418 }
419 impl<'tcx> TaitConstraintLocator<'tcx> {
420 fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
421 if !self.tcx.has_typeck_results(item_def_id) {
422 return ControlFlow::Continue(());
423 }
424
425 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
426 if !opaque_types_defined_by.contains(&self.opaque_def_id) {
428 return ControlFlow::Continue(());
429 }
430
431 if let Some(hidden_ty) = self
432 .tcx
433 .mir_borrowck(item_def_id)
434 .ok()
435 .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
436 {
437 ControlFlow::Break((hidden_ty.span, item_def_id))
438 } else {
439 ControlFlow::Continue(())
440 }
441 }
442 }
443 impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
444 type NestedFilter = nested_filter::All;
445 type Result = ControlFlow<(Span, LocalDefId)>;
446 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
447 self.tcx
448 }
449 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
450 intravisit::walk_expr(self, ex)
451 }
452 fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
453 self.check(it.owner_id.def_id)?;
454 intravisit::walk_item(self, it)
455 }
456 fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
457 self.check(it.owner_id.def_id)?;
458 intravisit::walk_impl_item(self, it)
459 }
460 fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
461 self.check(it.owner_id.def_id)?;
462 intravisit::walk_trait_item(self, it)
463 }
464 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
465 intravisit::walk_foreign_item(self, it)
466 }
467 }
468
469 let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
470 match origin {
471 hir::OpaqueTyOrigin::FnReturn { parent, .. }
472 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
473 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
474 let impl_def_id = tcx.local_parent(parent);
475 for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
476 match assoc.kind {
477 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
478 if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
479 {
480 return Some(span);
481 }
482 }
483 ty::AssocKind::Type { .. } => {}
484 }
485 }
486
487 None
488 }
489 hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
490 tcx.hir_walk_toplevel_module(&mut locator).break_value()
491 }
492 }
493}
494
495fn sanity_check_found_hidden_type<'tcx>(
496 tcx: TyCtxt<'tcx>,
497 key: ty::OpaqueTypeKey<'tcx>,
498 mut ty: ty::ProvisionalHiddenType<'tcx>,
499) -> Result<(), ErrorGuaranteed> {
500 if ty.ty.is_ty_var() {
501 return Ok(());
503 }
504 if let ty::Alias(ty::Opaque, alias) = ty.ty.kind() {
505 if alias.def_id == key.def_id.to_def_id() && alias.args == key.args {
506 return Ok(());
509 }
510 }
511 let erase_re_vars = |ty: Ty<'tcx>| {
512 fold_regions(tcx, ty, |r, _| match r.kind() {
513 RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
514 _ => r,
515 })
516 };
517 ty.ty = erase_re_vars(ty.ty);
520 let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args);
522 let hidden_ty = erase_re_vars(hidden_ty);
523
524 if hidden_ty == ty.ty {
526 Ok(())
527 } else {
528 let span = tcx.def_span(key.def_id);
529 let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
530 Err(ty.build_mismatch_error(&other, tcx)?.emit())
531 }
532}
533
534fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
543 let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
544 let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
545 hir::GenericBound::Use(bounds, ..) => Some(bounds),
546 _ => None,
547 }) else {
548 return;
550 };
551
552 let mut expected_captures = UnordSet::default();
553 let mut shadowed_captures = UnordSet::default();
554 let mut seen_params = UnordMap::default();
555 let mut prev_non_lifetime_param = None;
556 for arg in precise_capturing_args {
557 let (hir_id, ident) = match *arg {
558 hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
559 hir_id,
560 ident,
561 ..
562 }) => {
563 if prev_non_lifetime_param.is_none() {
564 prev_non_lifetime_param = Some(ident);
565 }
566 (hir_id, ident)
567 }
568 hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
569 if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
570 tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
571 lifetime_span: ident.span,
572 name: ident.name,
573 other_span: prev_non_lifetime_param.span,
574 });
575 }
576 (hir_id, ident)
577 }
578 };
579
580 let ident = ident.normalize_to_macros_2_0();
581 if let Some(span) = seen_params.insert(ident, ident.span) {
582 tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
583 name: ident.name,
584 first_span: span,
585 second_span: ident.span,
586 });
587 }
588
589 match tcx.named_bound_var(hir_id) {
590 Some(ResolvedArg::EarlyBound(def_id)) => {
591 expected_captures.insert(def_id.to_def_id());
592
593 if let DefKind::LifetimeParam = tcx.def_kind(def_id)
599 && let Some(def_id) = tcx
600 .map_opaque_lifetime_to_parent_lifetime(def_id)
601 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
602 {
603 shadowed_captures.insert(def_id);
604 }
605 }
606 _ => {
607 tcx.dcx()
608 .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
609 }
610 }
611 }
612
613 let variances = tcx.variances_of(opaque_def_id);
614 let mut def_id = Some(opaque_def_id.to_def_id());
615 while let Some(generics) = def_id {
616 let generics = tcx.generics_of(generics);
617 def_id = generics.parent;
618
619 for param in &generics.own_params {
620 if expected_captures.contains(¶m.def_id) {
621 assert_eq!(
622 variances[param.index as usize],
623 ty::Invariant,
624 "precise captured param should be invariant"
625 );
626 continue;
627 }
628 if shadowed_captures.contains(¶m.def_id) {
632 continue;
633 }
634
635 match param.kind {
636 ty::GenericParamDefKind::Lifetime => {
637 let use_span = tcx.def_span(param.def_id);
638 let opaque_span = tcx.def_span(opaque_def_id);
639 if variances[param.index as usize] == ty::Invariant {
641 if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
642 && let Some(def_id) = tcx
643 .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
644 .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
645 {
646 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
647 opaque_span,
648 use_span,
649 param_span: tcx.def_span(def_id),
650 });
651 } else {
652 if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
653 tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
654 opaque_span,
655 param_span: tcx.def_span(param.def_id),
656 });
657 } else {
658 tcx.dcx().emit_err(errors::LifetimeNotCaptured {
663 opaque_span,
664 use_span: opaque_span,
665 param_span: use_span,
666 });
667 }
668 }
669 continue;
670 }
671 }
672 ty::GenericParamDefKind::Type { .. } => {
673 if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {
674 tcx.dcx().emit_err(errors::SelfTyNotCaptured {
676 trait_span: tcx.def_span(param.def_id),
677 opaque_span: tcx.def_span(opaque_def_id),
678 });
679 } else {
680 tcx.dcx().emit_err(errors::ParamNotCaptured {
682 param_span: tcx.def_span(param.def_id),
683 opaque_span: tcx.def_span(opaque_def_id),
684 kind: "type",
685 });
686 }
687 }
688 ty::GenericParamDefKind::Const { .. } => {
689 tcx.dcx().emit_err(errors::ParamNotCaptured {
691 param_span: tcx.def_span(param.def_id),
692 opaque_span: tcx.def_span(opaque_def_id),
693 kind: "const",
694 });
695 }
696 }
697 }
698 }
699}
700
701fn is_enum_of_nonnullable_ptr<'tcx>(
702 tcx: TyCtxt<'tcx>,
703 adt_def: AdtDef<'tcx>,
704 args: GenericArgsRef<'tcx>,
705) -> bool {
706 if adt_def.repr().inhibit_enum_layout_opt() {
707 return false;
708 }
709
710 let [var_one, var_two] = &adt_def.variants().raw[..] else {
711 return false;
712 };
713 let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
714 return false;
715 };
716 matches!(field.ty(tcx, args).kind(), ty::FnPtr(..) | ty::Ref(..))
717}
718
719fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
720 if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
721 if match tcx.type_of(def_id).instantiate_identity().kind() {
722 ty::RawPtr(_, _) => false,
723 ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
724 _ => true,
725 } {
726 tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
727 }
728 }
729}
730
731pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
732 let mut res = Ok(());
733 let generics = tcx.generics_of(def_id);
734
735 for param in &generics.own_params {
736 match param.kind {
737 ty::GenericParamDefKind::Lifetime { .. } => {}
738 ty::GenericParamDefKind::Type { has_default, .. } => {
739 if has_default {
740 tcx.ensure_ok().type_of(param.def_id);
741 }
742 }
743 ty::GenericParamDefKind::Const { has_default, .. } => {
744 tcx.ensure_ok().type_of(param.def_id);
745 if has_default {
746 let ct = tcx.const_param_default(param.def_id).skip_binder();
748 if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
749 tcx.ensure_ok().type_of(uv.def);
750 }
751 }
752 }
753 }
754 }
755
756 match tcx.def_kind(def_id) {
757 DefKind::Static { .. } => {
758 tcx.ensure_ok().generics_of(def_id);
759 tcx.ensure_ok().type_of(def_id);
760 tcx.ensure_ok().predicates_of(def_id);
761
762 check_static_inhabited(tcx, def_id);
763 check_static_linkage(tcx, def_id);
764 let ty = tcx.type_of(def_id).instantiate_identity();
765 res = res.and(wfcheck::check_static_item(
766 tcx, def_id, ty, true,
767 ));
768
769 return res;
773 }
774 DefKind::Enum => {
775 tcx.ensure_ok().generics_of(def_id);
776 tcx.ensure_ok().type_of(def_id);
777 tcx.ensure_ok().predicates_of(def_id);
778 crate::collect::lower_enum_variant_types(tcx, def_id);
779 check_enum(tcx, def_id);
780 check_variances_for_type_defn(tcx, def_id);
781 }
782 DefKind::Fn => {
783 tcx.ensure_ok().generics_of(def_id);
784 tcx.ensure_ok().type_of(def_id);
785 tcx.ensure_ok().predicates_of(def_id);
786 tcx.ensure_ok().fn_sig(def_id);
787 tcx.ensure_ok().codegen_fn_attrs(def_id);
788 if let Some(i) = tcx.intrinsic(def_id) {
789 intrinsic::check_intrinsic_type(
790 tcx,
791 def_id,
792 tcx.def_ident_span(def_id).unwrap(),
793 i.name,
794 )
795 }
796 }
797 DefKind::Impl { of_trait } => {
798 tcx.ensure_ok().generics_of(def_id);
799 tcx.ensure_ok().type_of(def_id);
800 tcx.ensure_ok().predicates_of(def_id);
801 tcx.ensure_ok().associated_items(def_id);
802 check_diagnostic_attrs(tcx, def_id);
803 if of_trait {
804 let impl_trait_header = tcx.impl_trait_header(def_id);
805 res = res.and(
806 tcx.ensure_ok()
807 .coherent_trait(impl_trait_header.trait_ref.instantiate_identity().def_id),
808 );
809
810 if res.is_ok() {
811 check_impl_items_against_trait(tcx, def_id, impl_trait_header);
815 }
816 }
817 }
818 DefKind::Trait => {
819 tcx.ensure_ok().generics_of(def_id);
820 tcx.ensure_ok().trait_def(def_id);
821 tcx.ensure_ok().explicit_super_predicates_of(def_id);
822 tcx.ensure_ok().predicates_of(def_id);
823 tcx.ensure_ok().associated_items(def_id);
824 let assoc_items = tcx.associated_items(def_id);
825 check_diagnostic_attrs(tcx, def_id);
826
827 for &assoc_item in assoc_items.in_definition_order() {
828 match assoc_item.kind {
829 ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
830 let trait_args = GenericArgs::identity_for_item(tcx, def_id);
831 let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
832 tcx,
833 assoc_item,
834 assoc_item,
835 ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
836 );
837 }
838 _ => {}
839 }
840 }
841 }
842 DefKind::TraitAlias => {
843 tcx.ensure_ok().generics_of(def_id);
844 tcx.ensure_ok().explicit_implied_predicates_of(def_id);
845 tcx.ensure_ok().explicit_super_predicates_of(def_id);
846 tcx.ensure_ok().predicates_of(def_id);
847 }
848 def_kind @ (DefKind::Struct | DefKind::Union) => {
849 tcx.ensure_ok().generics_of(def_id);
850 tcx.ensure_ok().type_of(def_id);
851 tcx.ensure_ok().predicates_of(def_id);
852
853 let adt = tcx.adt_def(def_id).non_enum_variant();
854 for f in adt.fields.iter() {
855 tcx.ensure_ok().generics_of(f.did);
856 tcx.ensure_ok().type_of(f.did);
857 tcx.ensure_ok().predicates_of(f.did);
858 }
859
860 if let Some((_, ctor_def_id)) = adt.ctor {
861 crate::collect::lower_variant_ctor(tcx, ctor_def_id.expect_local());
862 }
863 match def_kind {
864 DefKind::Struct => check_struct(tcx, def_id),
865 DefKind::Union => check_union(tcx, def_id),
866 _ => unreachable!(),
867 }
868 check_variances_for_type_defn(tcx, def_id);
869 }
870 DefKind::OpaqueTy => {
871 check_opaque_precise_captures(tcx, def_id);
872
873 let origin = tcx.local_opaque_ty_origin(def_id);
874 if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
875 | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
876 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
877 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
878 {
879 } else {
881 check_opaque(tcx, def_id);
882 }
883
884 tcx.ensure_ok().predicates_of(def_id);
885 tcx.ensure_ok().explicit_item_bounds(def_id);
886 tcx.ensure_ok().explicit_item_self_bounds(def_id);
887 if tcx.is_conditionally_const(def_id) {
888 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
889 tcx.ensure_ok().const_conditions(def_id);
890 }
891
892 return res;
896 }
897 DefKind::Const => {
898 tcx.ensure_ok().generics_of(def_id);
899 tcx.ensure_ok().type_of(def_id);
900 tcx.ensure_ok().predicates_of(def_id);
901
902 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
903 let ty = tcx.type_of(def_id).instantiate_identity();
904 let ty_span = tcx.ty_span(def_id);
905 let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
906 wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
907 wfcx.register_bound(
908 traits::ObligationCause::new(
909 ty_span,
910 def_id,
911 ObligationCauseCode::SizedConstOrStatic,
912 ),
913 tcx.param_env(def_id),
914 ty,
915 tcx.require_lang_item(LangItem::Sized, ty_span),
916 );
917 check_where_clauses(wfcx, def_id);
918
919 if find_attr!(tcx.get_all_attrs(def_id), AttributeKind::TypeConst(_)) {
920 wfcheck::check_type_const(wfcx, def_id, ty, true)?;
921 }
922 Ok(())
923 }));
924
925 return res;
929 }
930 DefKind::TyAlias => {
931 tcx.ensure_ok().generics_of(def_id);
932 tcx.ensure_ok().type_of(def_id);
933 tcx.ensure_ok().predicates_of(def_id);
934 check_type_alias_type_params_are_used(tcx, def_id);
935 if tcx.type_alias_is_lazy(def_id) {
936 res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
937 let ty = tcx.type_of(def_id).instantiate_identity();
938 let span = tcx.def_span(def_id);
939 let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
940 wfcx.register_wf_obligation(
941 span,
942 Some(WellFormedLoc::Ty(def_id)),
943 item_ty.into(),
944 );
945 check_where_clauses(wfcx, def_id);
946 Ok(())
947 }));
948 check_variances_for_type_defn(tcx, def_id);
949 }
950
951 return res;
955 }
956 DefKind::ForeignMod => {
957 let it = tcx.hir_expect_item(def_id);
958 let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
959 return Ok(());
960 };
961
962 check_abi(tcx, it.hir_id(), it.span, abi);
963
964 for &item in items {
965 let def_id = item.owner_id.def_id;
966
967 let generics = tcx.generics_of(def_id);
968 let own_counts = generics.own_counts();
969 if generics.own_params.len() - own_counts.lifetimes != 0 {
970 let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
971 (_, 0) => ("type", "types", Some("u32")),
972 (0, _) => ("const", "consts", None),
975 _ => ("type or const", "types or consts", None),
976 };
977 let span = tcx.def_span(def_id);
978 struct_span_code_err!(
979 tcx.dcx(),
980 span,
981 E0044,
982 "foreign items may not have {kinds} parameters",
983 )
984 .with_span_label(span, format!("can't have {kinds} parameters"))
985 .with_help(
986 format!(
989 "replace the {} parameters with concrete {}{}",
990 kinds,
991 kinds_pl,
992 egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
993 ),
994 )
995 .emit();
996 }
997
998 tcx.ensure_ok().generics_of(def_id);
999 tcx.ensure_ok().type_of(def_id);
1000 tcx.ensure_ok().predicates_of(def_id);
1001 if tcx.is_conditionally_const(def_id) {
1002 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1003 tcx.ensure_ok().const_conditions(def_id);
1004 }
1005 match tcx.def_kind(def_id) {
1006 DefKind::Fn => {
1007 tcx.ensure_ok().codegen_fn_attrs(def_id);
1008 tcx.ensure_ok().fn_sig(def_id);
1009 let item = tcx.hir_foreign_item(item);
1010 let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { bug!() };
1011 check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1012 }
1013 DefKind::Static { .. } => {
1014 tcx.ensure_ok().codegen_fn_attrs(def_id);
1015 }
1016 _ => (),
1017 }
1018 }
1019 }
1020 DefKind::Closure => {
1021 tcx.ensure_ok().codegen_fn_attrs(def_id);
1025 return res;
1033 }
1034 DefKind::AssocFn => {
1035 tcx.ensure_ok().codegen_fn_attrs(def_id);
1036 tcx.ensure_ok().type_of(def_id);
1037 tcx.ensure_ok().fn_sig(def_id);
1038 tcx.ensure_ok().predicates_of(def_id);
1039 res = res.and(check_associated_item(tcx, def_id));
1040 let assoc_item = tcx.associated_item(def_id);
1041 match assoc_item.container {
1042 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1043 ty::AssocContainer::Trait => {
1044 res = res.and(check_trait_item(tcx, def_id));
1045 }
1046 }
1047
1048 return res;
1052 }
1053 DefKind::AssocConst => {
1054 tcx.ensure_ok().type_of(def_id);
1055 tcx.ensure_ok().predicates_of(def_id);
1056 res = res.and(check_associated_item(tcx, def_id));
1057 let assoc_item = tcx.associated_item(def_id);
1058 match assoc_item.container {
1059 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1060 ty::AssocContainer::Trait => {
1061 res = res.and(check_trait_item(tcx, def_id));
1062 }
1063 }
1064
1065 return res;
1069 }
1070 DefKind::AssocTy => {
1071 tcx.ensure_ok().predicates_of(def_id);
1072 res = res.and(check_associated_item(tcx, def_id));
1073
1074 let assoc_item = tcx.associated_item(def_id);
1075 let has_type = match assoc_item.container {
1076 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1077 ty::AssocContainer::Trait => {
1078 tcx.ensure_ok().explicit_item_bounds(def_id);
1079 tcx.ensure_ok().explicit_item_self_bounds(def_id);
1080 if tcx.is_conditionally_const(def_id) {
1081 tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1082 tcx.ensure_ok().const_conditions(def_id);
1083 }
1084 res = res.and(check_trait_item(tcx, def_id));
1085 assoc_item.defaultness(tcx).has_value()
1086 }
1087 };
1088 if has_type {
1089 tcx.ensure_ok().type_of(def_id);
1090 }
1091
1092 return res;
1096 }
1097
1098 DefKind::AnonConst | DefKind::InlineConst => return res,
1102 _ => {}
1103 }
1104 let node = tcx.hir_node_by_def_id(def_id);
1105 res.and(match node {
1106 hir::Node::Crate(_) => bug!("check_well_formed cannot be applied to the crate root"),
1107 hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1108 hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1109 _ => unreachable!("{node:?}"),
1110 })
1111}
1112
1113pub(super) fn check_diagnostic_attrs(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1114 let _ = OnUnimplementedDirective::of_item(tcx, def_id.to_def_id());
1116}
1117
1118pub(super) fn check_specialization_validity<'tcx>(
1119 tcx: TyCtxt<'tcx>,
1120 trait_def: &ty::TraitDef,
1121 trait_item: ty::AssocItem,
1122 impl_id: DefId,
1123 impl_item: DefId,
1124) {
1125 let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1126 let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1127 if parent.is_from_trait() {
1128 None
1129 } else {
1130 Some((parent, parent.item(tcx, trait_item.def_id)))
1131 }
1132 });
1133
1134 let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1135 match parent_item {
1136 Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1139 Some(Err(parent_impl.def_id()))
1140 }
1141
1142 Some(_) => Some(Ok(())),
1144
1145 None => {
1149 if tcx.defaultness(parent_impl.def_id()).is_default() {
1150 None
1151 } else {
1152 Some(Err(parent_impl.def_id()))
1153 }
1154 }
1155 }
1156 });
1157
1158 let result = opt_result.unwrap_or(Ok(()));
1161
1162 if let Err(parent_impl) = result {
1163 if !tcx.is_impl_trait_in_trait(impl_item) {
1164 report_forbidden_specialization(tcx, impl_item, parent_impl);
1165 } else {
1166 tcx.dcx().delayed_bug(format!("parent item: {parent_impl:?} not marked as default"));
1167 }
1168 }
1169}
1170
1171fn check_impl_items_against_trait<'tcx>(
1172 tcx: TyCtxt<'tcx>,
1173 impl_id: LocalDefId,
1174 impl_trait_header: ty::ImplTraitHeader<'tcx>,
1175) {
1176 let trait_ref = impl_trait_header.trait_ref.instantiate_identity();
1177 if trait_ref.references_error() {
1181 return;
1182 }
1183
1184 let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1185
1186 match impl_trait_header.polarity {
1188 ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1189 ty::ImplPolarity::Negative => {
1190 if let [first_item_ref, ..] = impl_item_refs {
1191 let first_item_span = tcx.def_span(first_item_ref);
1192 struct_span_code_err!(
1193 tcx.dcx(),
1194 first_item_span,
1195 E0749,
1196 "negative impls cannot have any items"
1197 )
1198 .emit();
1199 }
1200 return;
1201 }
1202 }
1203
1204 let trait_def = tcx.trait_def(trait_ref.def_id);
1205
1206 let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1207
1208 for &impl_item in impl_item_refs {
1209 let ty_impl_item = tcx.associated_item(impl_item);
1210 let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1211 Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1212 Err(ErrorGuaranteed { .. }) => continue,
1213 };
1214
1215 let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
1216
1217 if res.is_ok() {
1218 match ty_impl_item.kind {
1219 ty::AssocKind::Fn { .. } => {
1220 compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1221 tcx,
1222 ty_impl_item,
1223 ty_trait_item,
1224 tcx.impl_trait_ref(ty_impl_item.container_id(tcx)).instantiate_identity(),
1225 );
1226 }
1227 ty::AssocKind::Const { .. } => {}
1228 ty::AssocKind::Type { .. } => {}
1229 }
1230 }
1231
1232 if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1233 tcx.emit_node_span_lint(
1234 rustc_lint_defs::builtin::DEAD_CODE,
1235 tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1236 tcx.def_span(ty_impl_item.def_id),
1237 errors::UselessImplItem,
1238 )
1239 }
1240
1241 check_specialization_validity(
1242 tcx,
1243 trait_def,
1244 ty_trait_item,
1245 impl_id.to_def_id(),
1246 impl_item,
1247 );
1248 }
1249
1250 if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1251 let mut missing_items = Vec::new();
1253
1254 let mut must_implement_one_of: Option<&[Ident]> =
1255 trait_def.must_implement_one_of.as_deref();
1256
1257 for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1258 let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1259
1260 let is_implemented = leaf_def
1261 .as_ref()
1262 .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1263
1264 if !is_implemented
1265 && tcx.defaultness(impl_id).is_final()
1266 && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1268 {
1269 missing_items.push(tcx.associated_item(trait_item_id));
1270 }
1271
1272 let is_implemented_here =
1274 leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1275
1276 if !is_implemented_here {
1277 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1278 match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1279 EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1280 tcx,
1281 full_impl_span,
1282 trait_item_id,
1283 feature,
1284 reason,
1285 issue,
1286 ),
1287
1288 EvalResult::Allow | EvalResult::Unmarked => {}
1290 }
1291 }
1292
1293 if let Some(required_items) = &must_implement_one_of {
1294 if is_implemented_here {
1295 let trait_item = tcx.associated_item(trait_item_id);
1296 if required_items.contains(&trait_item.ident(tcx)) {
1297 must_implement_one_of = None;
1298 }
1299 }
1300 }
1301
1302 if let Some(leaf_def) = &leaf_def
1303 && !leaf_def.is_final()
1304 && let def_id = leaf_def.item.def_id
1305 && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1306 {
1307 let def_kind = tcx.def_kind(def_id);
1308 let descr = tcx.def_kind_descr(def_kind, def_id);
1309 let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1310 (
1311 format!("async {descr} in trait cannot be specialized"),
1312 "async functions in traits",
1313 )
1314 } else {
1315 (
1316 format!(
1317 "{descr} with return-position `impl Trait` in trait cannot be specialized"
1318 ),
1319 "return position `impl Trait` in traits",
1320 )
1321 };
1322 tcx.dcx()
1323 .struct_span_err(tcx.def_span(def_id), msg)
1324 .with_note(format!(
1325 "specialization behaves in inconsistent and surprising ways with \
1326 {feature}, and for now is disallowed"
1327 ))
1328 .emit();
1329 }
1330 }
1331
1332 if !missing_items.is_empty() {
1333 let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1334 missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1335 }
1336
1337 if let Some(missing_items) = must_implement_one_of {
1338 let attr_span = find_attr!(tcx.get_all_attrs(trait_ref.def_id), AttributeKind::RustcMustImplementOneOf {attr_span, ..} => *attr_span);
1339
1340 missing_items_must_implement_one_of_err(
1341 tcx,
1342 tcx.def_span(impl_id),
1343 missing_items,
1344 attr_span,
1345 );
1346 }
1347 }
1348}
1349
1350fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1351 let t = tcx.type_of(def_id).instantiate_identity();
1352 if let ty::Adt(def, args) = t.kind()
1353 && def.is_struct()
1354 {
1355 let fields = &def.non_enum_variant().fields;
1356 if fields.is_empty() {
1357 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1358 return;
1359 }
1360
1361 let array_field = &fields[FieldIdx::ZERO];
1362 let array_ty = array_field.ty(tcx, args);
1363 let ty::Array(element_ty, len_const) = array_ty.kind() else {
1364 struct_span_code_err!(
1365 tcx.dcx(),
1366 sp,
1367 E0076,
1368 "SIMD vector's only field must be an array"
1369 )
1370 .with_span_label(tcx.def_span(array_field.did), "not an array")
1371 .emit();
1372 return;
1373 };
1374
1375 if let Some(second_field) = fields.get(FieldIdx::ONE) {
1376 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1377 .with_span_label(tcx.def_span(second_field.did), "excess field")
1378 .emit();
1379 return;
1380 }
1381
1382 if let Some(len) = len_const.try_to_target_usize(tcx) {
1387 if len == 0 {
1388 struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1389 return;
1390 } else if len > MAX_SIMD_LANES {
1391 struct_span_code_err!(
1392 tcx.dcx(),
1393 sp,
1394 E0075,
1395 "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1396 )
1397 .emit();
1398 return;
1399 }
1400 }
1401
1402 match element_ty.kind() {
1407 ty::Param(_) => (), ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), _ => {
1410 struct_span_code_err!(
1411 tcx.dcx(),
1412 sp,
1413 E0077,
1414 "SIMD vector element type should be a \
1415 primitive scalar (integer/float/pointer) type"
1416 )
1417 .emit();
1418 return;
1419 }
1420 }
1421 }
1422}
1423
1424#[tracing::instrument(skip(tcx), level = "debug")]
1425fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalable: ScalableElt) {
1426 let ty = tcx.type_of(def_id).instantiate_identity();
1427 let ty::Adt(def, args) = ty.kind() else { return };
1428 if !def.is_struct() {
1429 tcx.dcx().delayed_bug("`rustc_scalable_vector` applied to non-struct");
1430 return;
1431 }
1432
1433 let fields = &def.non_enum_variant().fields;
1434 match scalable {
1435 ScalableElt::ElementCount(..) if fields.is_empty() => {
1436 let mut err =
1437 tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1438 err.help("scalable vector types' only field must be a primitive scalar type");
1439 err.emit();
1440 return;
1441 }
1442 ScalableElt::ElementCount(..) if fields.len() >= 2 => {
1443 tcx.dcx().struct_span_err(span, "scalable vectors cannot have multiple fields").emit();
1444 return;
1445 }
1446 ScalableElt::Container if fields.is_empty() => {
1447 let mut err =
1448 tcx.dcx().struct_span_err(span, "scalable vectors must have a single field");
1449 err.help("tuples of scalable vectors can only contain multiple of the same scalable vector type");
1450 err.emit();
1451 return;
1452 }
1453 _ => {}
1454 }
1455
1456 match scalable {
1457 ScalableElt::ElementCount(..) => {
1458 let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args);
1459
1460 match element_ty.kind() {
1464 ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Bool => (),
1465 _ => {
1466 let mut err = tcx.dcx().struct_span_err(
1467 span,
1468 "element type of a scalable vector must be a primitive scalar",
1469 );
1470 err.help("only `u*`, `i*`, `f*` and `bool` types are accepted");
1471 err.emit();
1472 }
1473 }
1474 }
1475 ScalableElt::Container => {
1476 let mut prev_field_ty = None;
1477 for field in fields.iter() {
1478 let element_ty = field.ty(tcx, args);
1479 if let ty::Adt(def, _) = element_ty.kind()
1480 && def.repr().scalable()
1481 {
1482 match def
1483 .repr()
1484 .scalable
1485 .expect("`repr().scalable.is_some()` != `repr().scalable()`")
1486 {
1487 ScalableElt::ElementCount(_) => { }
1488 ScalableElt::Container => {
1489 tcx.dcx().span_err(
1490 tcx.def_span(field.did),
1491 "scalable vector structs cannot contain other scalable vector structs",
1492 );
1493 break;
1494 }
1495 }
1496 } else {
1497 tcx.dcx().span_err(
1498 tcx.def_span(field.did),
1499 "scalable vector structs can only have scalable vector fields",
1500 );
1501 break;
1502 }
1503
1504 if let Some(prev_ty) = prev_field_ty.replace(element_ty)
1505 && prev_ty != element_ty
1506 {
1507 tcx.dcx().span_err(
1508 tcx.def_span(field.did),
1509 "all fields in a scalable vector struct must be the same type",
1510 );
1511 break;
1512 }
1513 }
1514 }
1515 }
1516}
1517
1518pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1519 let repr = def.repr();
1520 if repr.packed() {
1521 if let Some(reprs) = find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs)
1522 {
1523 for (r, _) in reprs {
1524 if let ReprPacked(pack) = r
1525 && let Some(repr_pack) = repr.pack
1526 && pack != &repr_pack
1527 {
1528 struct_span_code_err!(
1529 tcx.dcx(),
1530 sp,
1531 E0634,
1532 "type has conflicting packed representation hints"
1533 )
1534 .emit();
1535 }
1536 }
1537 }
1538 if repr.align.is_some() {
1539 struct_span_code_err!(
1540 tcx.dcx(),
1541 sp,
1542 E0587,
1543 "type has conflicting packed and align representation hints"
1544 )
1545 .emit();
1546 } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1547 let mut err = struct_span_code_err!(
1548 tcx.dcx(),
1549 sp,
1550 E0588,
1551 "packed type cannot transitively contain a `#[repr(align)]` type"
1552 );
1553
1554 err.span_note(
1555 tcx.def_span(def_spans[0].0),
1556 format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
1557 );
1558
1559 if def_spans.len() > 2 {
1560 let mut first = true;
1561 for (adt_def, span) in def_spans.iter().skip(1).rev() {
1562 let ident = tcx.item_name(*adt_def);
1563 err.span_note(
1564 *span,
1565 if first {
1566 format!(
1567 "`{}` contains a field of type `{}`",
1568 tcx.type_of(def.did()).instantiate_identity(),
1569 ident
1570 )
1571 } else {
1572 format!("...which contains a field of type `{ident}`")
1573 },
1574 );
1575 first = false;
1576 }
1577 }
1578
1579 err.emit();
1580 }
1581 }
1582}
1583
1584pub(super) fn check_packed_inner(
1585 tcx: TyCtxt<'_>,
1586 def_id: DefId,
1587 stack: &mut Vec<DefId>,
1588) -> Option<Vec<(DefId, Span)>> {
1589 if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1590 if def.is_struct() || def.is_union() {
1591 if def.repr().align.is_some() {
1592 return Some(vec![(def.did(), DUMMY_SP)]);
1593 }
1594
1595 stack.push(def_id);
1596 for field in &def.non_enum_variant().fields {
1597 if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1598 && !stack.contains(&def.did())
1599 && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1600 {
1601 defs.push((def.did(), field.ident(tcx).span));
1602 return Some(defs);
1603 }
1604 }
1605 stack.pop();
1606 }
1607 }
1608
1609 None
1610}
1611
1612pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1613 if !adt.repr().transparent() {
1614 return;
1615 }
1616
1617 if adt.is_union() && !tcx.features().transparent_unions() {
1618 feature_err(
1619 &tcx.sess,
1620 sym::transparent_unions,
1621 tcx.def_span(adt.did()),
1622 "transparent unions are unstable",
1623 )
1624 .emit();
1625 }
1626
1627 if adt.variants().len() != 1 {
1628 bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1629 return;
1631 }
1632
1633 let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1634 struct FieldInfo<'tcx> {
1636 span: Span,
1637 trivial: bool,
1638 ty: Ty<'tcx>,
1639 }
1640
1641 let field_infos = adt.all_fields().map(|field| {
1642 let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1643 let layout = tcx.layout_of(typing_env.as_query_input(ty));
1644 let span = tcx.hir_span_if_local(field.did).unwrap();
1646 let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1647 FieldInfo { span, trivial, ty }
1648 });
1649
1650 let non_trivial_fields = field_infos
1651 .clone()
1652 .filter_map(|field| if !field.trivial { Some(field.span) } else { None });
1653 let non_trivial_count = non_trivial_fields.clone().count();
1654 if non_trivial_count >= 2 {
1655 bad_non_zero_sized_fields(
1656 tcx,
1657 adt,
1658 non_trivial_count,
1659 non_trivial_fields,
1660 tcx.def_span(adt.did()),
1661 );
1662 return;
1663 }
1664
1665 struct UnsuitedInfo<'tcx> {
1668 ty: Ty<'tcx>,
1670 reason: UnsuitedReason,
1671 }
1672 enum UnsuitedReason {
1673 NonExhaustive,
1674 PrivateField,
1675 ReprC,
1676 }
1677
1678 fn check_unsuited<'tcx>(
1679 tcx: TyCtxt<'tcx>,
1680 typing_env: ty::TypingEnv<'tcx>,
1681 ty: Ty<'tcx>,
1682 ) -> ControlFlow<UnsuitedInfo<'tcx>> {
1683 let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1685 match ty.kind() {
1686 ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1687 ty::Array(ty, _) => check_unsuited(tcx, typing_env, *ty),
1688 ty::Adt(def, args) => {
1689 if !def.did().is_local()
1690 && !find_attr!(tcx.get_all_attrs(def.did()), AttributeKind::PubTransparent(_))
1691 {
1692 let non_exhaustive = def.is_variant_list_non_exhaustive()
1693 || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1694 let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1695 if non_exhaustive || has_priv {
1696 return ControlFlow::Break(UnsuitedInfo {
1697 ty,
1698 reason: if non_exhaustive {
1699 UnsuitedReason::NonExhaustive
1700 } else {
1701 UnsuitedReason::PrivateField
1702 },
1703 });
1704 }
1705 }
1706 if def.repr().c() {
1707 return ControlFlow::Break(UnsuitedInfo { ty, reason: UnsuitedReason::ReprC });
1708 }
1709 def.all_fields()
1710 .map(|field| field.ty(tcx, args))
1711 .try_for_each(|t| check_unsuited(tcx, typing_env, t))
1712 }
1713 _ => ControlFlow::Continue(()),
1714 }
1715 }
1716
1717 let mut prev_unsuited_1zst = false;
1718 for field in field_infos {
1719 if field.trivial
1720 && let Some(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1721 {
1722 if non_trivial_count > 0 || prev_unsuited_1zst {
1725 tcx.node_span_lint(
1726 REPR_TRANSPARENT_NON_ZST_FIELDS,
1727 tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1728 field.span,
1729 |lint| {
1730 let title = match unsuited.reason {
1731 UnsuitedReason::NonExhaustive => "external non-exhaustive types",
1732 UnsuitedReason::PrivateField => "external types with private fields",
1733 UnsuitedReason::ReprC => "`repr(C)` types",
1734 };
1735 lint.primary_message(
1736 format!("zero-sized fields in `repr(transparent)` cannot contain {title}"),
1737 );
1738 let note = match unsuited.reason {
1739 UnsuitedReason::NonExhaustive => "is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future.",
1740 UnsuitedReason::PrivateField => "contains private fields, so it could become non-zero-sized in the future.",
1741 UnsuitedReason::ReprC => "is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets.",
1742 };
1743 lint.note(format!(
1744 "this field contains `{field_ty}`, which {note}",
1745 field_ty = unsuited.ty,
1746 ));
1747 },
1748 );
1749 } else {
1750 prev_unsuited_1zst = true;
1751 }
1752 }
1753 }
1754}
1755
1756#[allow(trivial_numeric_casts)]
1757fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1758 let def = tcx.adt_def(def_id);
1759 def.destructor(tcx); if def.variants().is_empty() {
1762 find_attr!(
1763 tcx.get_all_attrs(def_id),
1764 attrs::AttributeKind::Repr { reprs, first_span } => {
1765 struct_span_code_err!(
1766 tcx.dcx(),
1767 reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1768 E0084,
1769 "unsupported representation for zero-variant enum"
1770 )
1771 .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1772 .emit();
1773 }
1774 );
1775 }
1776
1777 for v in def.variants() {
1778 if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1779 tcx.ensure_ok().typeck(discr_def_id.expect_local());
1780 }
1781 }
1782
1783 if def.repr().int.is_none() {
1784 let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1785 let get_disr = |var: &ty::VariantDef| match var.discr {
1786 ty::VariantDiscr::Explicit(disr) => Some(disr),
1787 ty::VariantDiscr::Relative(_) => None,
1788 };
1789
1790 let non_unit = def.variants().iter().find(|var| !is_unit(var));
1791 let disr_unit =
1792 def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1793 let disr_non_unit =
1794 def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1795
1796 if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1797 let mut err = struct_span_code_err!(
1798 tcx.dcx(),
1799 tcx.def_span(def_id),
1800 E0732,
1801 "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1802 );
1803 if let Some(disr_non_unit) = disr_non_unit {
1804 err.span_label(
1805 tcx.def_span(disr_non_unit),
1806 "explicit discriminant on non-unit variant specified here",
1807 );
1808 } else {
1809 err.span_label(
1810 tcx.def_span(disr_unit.unwrap()),
1811 "explicit discriminant specified here",
1812 );
1813 err.span_label(
1814 tcx.def_span(non_unit.unwrap().def_id),
1815 "non-unit discriminant declared here",
1816 );
1817 }
1818 err.emit();
1819 }
1820 }
1821
1822 detect_discriminant_duplicate(tcx, def);
1823 check_transparent(tcx, def);
1824}
1825
1826fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1828 let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1831 let var = adt.variant(idx); let (span, display_discr) = match var.discr {
1833 ty::VariantDiscr::Explicit(discr_def_id) => {
1834 if let hir::Node::AnonConst(expr) =
1836 tcx.hir_node_by_def_id(discr_def_id.expect_local())
1837 && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1838 && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1839 && *lit_value != dis.val
1840 {
1841 (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1842 } else {
1843 (tcx.def_span(discr_def_id), format!("`{dis}`"))
1845 }
1846 }
1847 ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1849 ty::VariantDiscr::Relative(distance_to_explicit) => {
1850 if let Some(explicit_idx) =
1855 idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1856 {
1857 let explicit_variant = adt.variant(explicit_idx);
1858 let ve_ident = var.name;
1859 let ex_ident = explicit_variant.name;
1860 let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1861
1862 err.span_label(
1863 tcx.def_span(explicit_variant.def_id),
1864 format!(
1865 "discriminant for `{ve_ident}` incremented from this startpoint \
1866 (`{ex_ident}` + {distance_to_explicit} {sp} later \
1867 => `{ve_ident}` = {dis})"
1868 ),
1869 );
1870 }
1871
1872 (tcx.def_span(var.def_id), format!("`{dis}`"))
1873 }
1874 };
1875
1876 err.span_label(span, format!("{display_discr} assigned here"));
1877 };
1878
1879 let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1880
1881 let mut i = 0;
1888 while i < discrs.len() {
1889 let var_i_idx = discrs[i].0;
1890 let mut error: Option<Diag<'_, _>> = None;
1891
1892 let mut o = i + 1;
1893 while o < discrs.len() {
1894 let var_o_idx = discrs[o].0;
1895
1896 if discrs[i].1.val == discrs[o].1.val {
1897 let err = error.get_or_insert_with(|| {
1898 let mut ret = struct_span_code_err!(
1899 tcx.dcx(),
1900 tcx.def_span(adt.did()),
1901 E0081,
1902 "discriminant value `{}` assigned more than once",
1903 discrs[i].1,
1904 );
1905
1906 report(discrs[i].1, var_i_idx, &mut ret);
1907
1908 ret
1909 });
1910
1911 report(discrs[o].1, var_o_idx, err);
1912
1913 discrs[o] = *discrs.last().unwrap();
1915 discrs.pop();
1916 } else {
1917 o += 1;
1918 }
1919 }
1920
1921 if let Some(e) = error {
1922 e.emit();
1923 }
1924
1925 i += 1;
1926 }
1927}
1928
1929fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1930 if tcx.type_alias_is_lazy(def_id) {
1931 return;
1934 }
1935
1936 let generics = tcx.generics_of(def_id);
1937 if generics.own_counts().types == 0 {
1938 return;
1939 }
1940
1941 let ty = tcx.type_of(def_id).instantiate_identity();
1942 if ty.references_error() {
1943 return;
1945 }
1946
1947 let bounded_params = LazyCell::new(|| {
1949 tcx.explicit_predicates_of(def_id)
1950 .predicates
1951 .iter()
1952 .filter_map(|(predicate, span)| {
1953 let bounded_ty = match predicate.kind().skip_binder() {
1954 ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1955 ty::ClauseKind::TypeOutlives(pred) => pred.0,
1956 _ => return None,
1957 };
1958 if let ty::Param(param) = bounded_ty.kind() {
1959 Some((param.index, span))
1960 } else {
1961 None
1962 }
1963 })
1964 .collect::<FxIndexMap<_, _>>()
1970 });
1971
1972 let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1973 for leaf in ty.walk() {
1974 if let GenericArgKind::Type(leaf_ty) = leaf.kind()
1975 && let ty::Param(param) = leaf_ty.kind()
1976 {
1977 debug!("found use of ty param {:?}", param);
1978 params_used.insert(param.index);
1979 }
1980 }
1981
1982 for param in &generics.own_params {
1983 if !params_used.contains(param.index)
1984 && let ty::GenericParamDefKind::Type { .. } = param.kind
1985 {
1986 let span = tcx.def_span(param.def_id);
1987 let param_name = Ident::new(param.name, span);
1988
1989 let has_explicit_bounds = bounded_params.is_empty()
1993 || (*bounded_params).get(¶m.index).is_some_and(|&&pred_sp| pred_sp != span);
1994 let const_param_help = !has_explicit_bounds;
1995
1996 let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
1997 span,
1998 param_name,
1999 param_def_kind: tcx.def_descr(param.def_id),
2000 help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
2001 usage_spans: vec![],
2002 const_param_help,
2003 });
2004 diag.code(E0091);
2005 diag.emit();
2006 }
2007 }
2008}
2009
2010fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
2019 let span = tcx.def_span(opaque_def_id);
2020 let mut err = struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
2021
2022 let mut label = false;
2023 if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
2024 let typeck_results = tcx.typeck(def_id);
2025 if visitor
2026 .returns
2027 .iter()
2028 .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
2029 .all(|ty| matches!(ty.kind(), ty::Never))
2030 {
2031 let spans = visitor
2032 .returns
2033 .iter()
2034 .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
2035 .map(|expr| expr.span)
2036 .collect::<Vec<Span>>();
2037 let span_len = spans.len();
2038 if span_len == 1 {
2039 err.span_label(spans[0], "this returned value is of `!` type");
2040 } else {
2041 let mut multispan: MultiSpan = spans.clone().into();
2042 for span in spans {
2043 multispan.push_span_label(span, "this returned value is of `!` type");
2044 }
2045 err.span_note(multispan, "these returned values have a concrete \"never\" type");
2046 }
2047 err.help("this error will resolve once the item's body returns a concrete type");
2048 } else {
2049 let mut seen = FxHashSet::default();
2050 seen.insert(span);
2051 err.span_label(span, "recursive opaque type");
2052 label = true;
2053 for (sp, ty) in visitor
2054 .returns
2055 .iter()
2056 .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
2057 .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
2058 {
2059 #[derive(Default)]
2060 struct OpaqueTypeCollector {
2061 opaques: Vec<DefId>,
2062 closures: Vec<DefId>,
2063 }
2064 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
2065 fn visit_ty(&mut self, t: Ty<'tcx>) {
2066 match *t.kind() {
2067 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
2068 self.opaques.push(def);
2069 }
2070 ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
2071 self.closures.push(def_id);
2072 t.super_visit_with(self);
2073 }
2074 _ => t.super_visit_with(self),
2075 }
2076 }
2077 }
2078
2079 let mut visitor = OpaqueTypeCollector::default();
2080 ty.visit_with(&mut visitor);
2081 for def_id in visitor.opaques {
2082 let ty_span = tcx.def_span(def_id);
2083 if !seen.contains(&ty_span) {
2084 let descr = if ty.is_impl_trait() { "opaque " } else { "" };
2085 err.span_label(ty_span, format!("returning this {descr}type `{ty}`"));
2086 seen.insert(ty_span);
2087 }
2088 err.span_label(sp, format!("returning here with type `{ty}`"));
2089 }
2090
2091 for closure_def_id in visitor.closures {
2092 let Some(closure_local_did) = closure_def_id.as_local() else {
2093 continue;
2094 };
2095 let typeck_results = tcx.typeck(closure_local_did);
2096
2097 let mut label_match = |ty: Ty<'_>, span| {
2098 for arg in ty.walk() {
2099 if let ty::GenericArgKind::Type(ty) = arg.kind()
2100 && let ty::Alias(
2101 ty::Opaque,
2102 ty::AliasTy { def_id: captured_def_id, .. },
2103 ) = *ty.kind()
2104 && captured_def_id == opaque_def_id.to_def_id()
2105 {
2106 err.span_label(
2107 span,
2108 format!(
2109 "{} captures itself here",
2110 tcx.def_descr(closure_def_id)
2111 ),
2112 );
2113 }
2114 }
2115 };
2116
2117 for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2119 {
2120 label_match(capture.place.ty(), capture.get_path_span(tcx));
2121 }
2122 if tcx.is_coroutine(closure_def_id)
2124 && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2125 {
2126 for interior_ty in &coroutine_layout.field_tys {
2127 label_match(interior_ty.ty, interior_ty.source_info.span);
2128 }
2129 }
2130 }
2131 }
2132 }
2133 }
2134 if !label {
2135 err.span_label(span, "cannot resolve opaque type");
2136 }
2137 err.emit()
2138}
2139
2140pub(super) fn check_coroutine_obligations(
2141 tcx: TyCtxt<'_>,
2142 def_id: LocalDefId,
2143) -> Result<(), ErrorGuaranteed> {
2144 debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
2145
2146 let typeck_results = tcx.typeck(def_id);
2147 let param_env = tcx.param_env(def_id);
2148
2149 debug!(?typeck_results.coroutine_stalled_predicates);
2150
2151 let mode = if tcx.next_trait_solver_globally() {
2152 TypingMode::borrowck(tcx, def_id)
2156 } else {
2157 TypingMode::analysis_in_body(tcx, def_id)
2158 };
2159
2160 let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2165
2166 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2167 for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2168 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2169 }
2170
2171 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2172 debug!(?errors);
2173 if !errors.is_empty() {
2174 return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2175 }
2176
2177 if !tcx.next_trait_solver_globally() {
2178 for (key, ty) in infcx.take_opaque_types() {
2181 let hidden_type = infcx.resolve_vars_if_possible(ty);
2182 let key = infcx.resolve_vars_if_possible(key);
2183 sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2184 }
2185 } else {
2186 let _ = infcx.take_opaque_types();
2189 }
2190
2191 Ok(())
2192}
2193
2194pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2195 tcx: TyCtxt<'tcx>,
2196 def_id: LocalDefId,
2197) -> Result<(), ErrorGuaranteed> {
2198 if !tcx.next_trait_solver_globally() {
2199 return Ok(());
2200 }
2201 let typeck_results = tcx.typeck(def_id);
2202 let param_env = tcx.param_env(def_id);
2203
2204 let typing_mode = TypingMode::borrowck(tcx, def_id);
2206 let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2207 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2208 for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2209 let predicate = fold_regions(tcx, *predicate, |_, _| {
2210 infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2211 });
2212 ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2213 }
2214
2215 let errors = ocx.evaluate_obligations_error_on_ambiguity();
2216 debug!(?errors);
2217 if errors.is_empty() { Ok(()) } else { Err(infcx.err_ctxt().report_fulfillment_errors(errors)) }
2218}