rustc_hir_analysis/check/
check.rs

1use std::cell::LazyCell;
2use std::ops::ControlFlow;
3
4use rustc_abi::{ExternAbi, FieldIdx};
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    // FIXME: This should be checked earlier, e.g. in `rustc_ast_lowering`, as this
58    // currently only guards function imports, function definitions, and function pointer types.
59    // Functions in trait declarations can still use "deprecated" ABIs without any warning.
60
61    match AbiMap::from_target(&tcx.sess.target).canonize_abi(abi, false) {
62        AbiMapping::Direct(..) => (),
63        // already erred in rustc_ast_lowering
64        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        // Function definitions that use `extern "custom"` must be naked functions.
81        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); // force the destructor to be evaluated
94
95    if def.repr().simd() {
96        check_simd(tcx, span, def_id);
97    }
98
99    check_transparent(tcx, def);
100    check_packed(tcx, span, def);
101}
102
103fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) {
104    let def = tcx.adt_def(def_id);
105    let span = tcx.def_span(def_id);
106    def.destructor(tcx); // force the destructor to be evaluated
107    check_transparent(tcx, def);
108    check_union_fields(tcx, span, def_id);
109    check_packed(tcx, span, def);
110}
111
112fn allowed_union_or_unsafe_field<'tcx>(
113    tcx: TyCtxt<'tcx>,
114    ty: Ty<'tcx>,
115    typing_env: ty::TypingEnv<'tcx>,
116    span: Span,
117) -> bool {
118    // HACK (not that bad of a hack don't worry): Some codegen tests don't even define proper
119    // impls for `Copy`. Let's short-circuit here for this validity check, since a lot of them
120    // use unions. We should eventually fix all the tests to define that lang item or use
121    // minicore stubs.
122    if ty.is_trivially_pure_clone_copy() {
123        return true;
124    }
125    // If `BikeshedGuaranteedNoDrop` is not defined in a `#[no_core]` test, fall back to `Copy`.
126    // This is an underapproximation of `BikeshedGuaranteedNoDrop`,
127    let def_id = tcx
128        .lang_items()
129        .get(LangItem::BikeshedGuaranteedNoDrop)
130        .unwrap_or_else(|| tcx.require_lang_item(LangItem::Copy, span));
131    let Ok(ty) = tcx.try_normalize_erasing_regions(typing_env, ty) else {
132        tcx.dcx().span_delayed_bug(span, "could not normalize field type");
133        return true;
134    };
135    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
136    infcx.predicate_must_hold_modulo_regions(&Obligation::new(
137        tcx,
138        ObligationCause::dummy_with_span(span),
139        param_env,
140        ty::TraitRef::new(tcx, def_id, [ty]),
141    ))
142}
143
144/// Check that the fields of the `union` do not need dropping.
145fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool {
146    let def = tcx.adt_def(item_def_id);
147    assert!(def.is_union());
148
149    let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
150    let args = ty::GenericArgs::identity_for_item(tcx, item_def_id);
151
152    for field in &def.non_enum_variant().fields {
153        if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
154            let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
155                // We are currently checking the type this field came from, so it must be local.
156                Some(Node::Field(field)) => (field.span, field.ty.span),
157                _ => unreachable!("mir field has to correspond to hir field"),
158            };
159            tcx.dcx().emit_err(errors::InvalidUnionField {
160                field_span,
161                sugg: errors::InvalidUnionFieldSuggestion {
162                    lo: ty_span.shrink_to_lo(),
163                    hi: ty_span.shrink_to_hi(),
164                },
165                note: (),
166            });
167            return false;
168        }
169    }
170
171    true
172}
173
174/// Check that a `static` is inhabited.
175fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
176    // Make sure statics are inhabited.
177    // Other parts of the compiler assume that there are no uninhabited places. In principle it
178    // would be enough to check this for `extern` statics, as statics with an initializer will
179    // have UB during initialization if they are uninhabited, but there also seems to be no good
180    // reason to allow any statics to be uninhabited.
181    let ty = tcx.type_of(def_id).instantiate_identity();
182    let span = tcx.def_span(def_id);
183    let layout = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
184        Ok(l) => l,
185        // Foreign statics that overflow their allowed size should emit an error
186        Err(LayoutError::SizeOverflow(_))
187            if matches!(tcx.def_kind(def_id), DefKind::Static{ .. }
188                if tcx.def_kind(tcx.local_parent(def_id)) == DefKind::ForeignMod) =>
189        {
190            tcx.dcx().emit_err(errors::TooLargeStatic { span });
191            return;
192        }
193        // Generic statics are rejected, but we still reach this case.
194        Err(e) => {
195            tcx.dcx().span_delayed_bug(span, format!("{e:?}"));
196            return;
197        }
198    };
199    if layout.is_uninhabited() {
200        tcx.node_span_lint(
201            UNINHABITED_STATIC,
202            tcx.local_def_id_to_hir_id(def_id),
203            span,
204            |lint| {
205                lint.primary_message("static of uninhabited type");
206                lint
207                .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
208            },
209        );
210    }
211}
212
213/// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo`
214/// projections that would result in "inheriting lifetimes".
215fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
216    let hir::OpaqueTy { origin, .. } = *tcx.hir_expect_opaque_ty(def_id);
217
218    // HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
219    // `async-std` (and `pub async fn` in general).
220    // Since rustdoc doesn't care about the hidden type behind `impl Trait`, just don't look at it!
221    // See https://github.com/rust-lang/rust/issues/75100
222    if tcx.sess.opts.actually_rustdoc {
223        return;
224    }
225
226    if tcx.type_of(def_id).instantiate_identity().references_error() {
227        return;
228    }
229    if check_opaque_for_cycles(tcx, def_id).is_err() {
230        return;
231    }
232
233    let _ = check_opaque_meets_bounds(tcx, def_id, origin);
234}
235
236/// Checks that an opaque type does not contain cycles.
237pub(super) fn check_opaque_for_cycles<'tcx>(
238    tcx: TyCtxt<'tcx>,
239    def_id: LocalDefId,
240) -> Result<(), ErrorGuaranteed> {
241    let args = GenericArgs::identity_for_item(tcx, def_id);
242
243    // First, try to look at any opaque expansion cycles, considering coroutine fields
244    // (even though these aren't necessarily true errors).
245    if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() {
246        let reported = opaque_type_cycle_error(tcx, def_id);
247        return Err(reported);
248    }
249
250    Ok(())
251}
252
253/// Check that the hidden type behind `impl Trait` actually implements `Trait`.
254///
255/// This is mostly checked at the places that specify the opaque type, but we
256/// check those cases in the `param_env` of that function, which may have
257/// bounds not on this opaque type:
258///
259/// ```ignore (illustrative)
260/// type X<T> = impl Clone;
261/// fn f<T: Clone>(t: T) -> X<T> {
262///     t
263/// }
264/// ```
265///
266/// Without this check the above code is incorrectly accepted: we would ICE if
267/// some tried, for example, to clone an `Option<X<&mut ()>>`.
268#[instrument(level = "debug", skip(tcx))]
269fn check_opaque_meets_bounds<'tcx>(
270    tcx: TyCtxt<'tcx>,
271    def_id: LocalDefId,
272    origin: hir::OpaqueTyOrigin<LocalDefId>,
273) -> Result<(), ErrorGuaranteed> {
274    let (span, definition_def_id) =
275        if let Some((span, def_id)) = best_definition_site_of_opaque(tcx, def_id, origin) {
276            (span, Some(def_id))
277        } else {
278            (tcx.def_span(def_id), None)
279        };
280
281    let defining_use_anchor = match origin {
282        hir::OpaqueTyOrigin::FnReturn { parent, .. }
283        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
284        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => parent,
285    };
286    let param_env = tcx.param_env(defining_use_anchor);
287
288    // FIXME(#132279): Once `PostBorrowckAnalysis` is supported in the old solver, this branch should be removed.
289    let infcx = tcx.infer_ctxt().build(if tcx.next_trait_solver_globally() {
290        TypingMode::post_borrowck_analysis(tcx, defining_use_anchor)
291    } else {
292        TypingMode::analysis_in_body(tcx, defining_use_anchor)
293    });
294    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
295
296    let args = match origin {
297        hir::OpaqueTyOrigin::FnReturn { parent, .. }
298        | hir::OpaqueTyOrigin::AsyncFn { parent, .. }
299        | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item(
300            tcx, parent,
301        )
302        .extend_to(tcx, def_id.to_def_id(), |param, _| {
303            tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
304        }),
305    };
306
307    let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args);
308
309    // `ReErased` regions appear in the "parent_args" of closures/coroutines.
310    // We're ignoring them here and replacing them with fresh region variables.
311    // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs.
312    //
313    // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it
314    // here rather than using ReErased.
315    let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args);
316    let hidden_ty = fold_regions(tcx, hidden_ty, |re, _dbi| match re.kind() {
317        ty::ReErased => infcx.next_region_var(RegionVariableOrigin::Misc(span)),
318        _ => re,
319    });
320
321    // HACK: We eagerly instantiate some bounds to report better errors for them...
322    // This isn't necessary for correctness, since we register these bounds when
323    // equating the opaque below, but we should clean this up in the new solver.
324    for (predicate, pred_span) in
325        tcx.explicit_item_bounds(def_id).iter_instantiated_copied(tcx, args)
326    {
327        let predicate = predicate.fold_with(&mut BottomUpFolder {
328            tcx,
329            ty_op: |ty| if ty == opaque_ty { hidden_ty } else { ty },
330            lt_op: |lt| lt,
331            ct_op: |ct| ct,
332        });
333
334        ocx.register_obligation(Obligation::new(
335            tcx,
336            ObligationCause::new(
337                span,
338                def_id,
339                ObligationCauseCode::OpaqueTypeBound(pred_span, definition_def_id),
340            ),
341            param_env,
342            predicate,
343        ));
344    }
345
346    let misc_cause = ObligationCause::misc(span, def_id);
347    // FIXME: We should just register the item bounds here, rather than equating.
348    // FIXME(const_trait_impl): When we do that, please make sure to also register
349    // the `[const]` bounds.
350    match ocx.eq(&misc_cause, param_env, opaque_ty, hidden_ty) {
351        Ok(()) => {}
352        Err(ty_err) => {
353            // Some types may be left "stranded" if they can't be reached
354            // from a lowered rustc_middle bound but they're mentioned in the HIR.
355            // This will happen, e.g., when a nested opaque is inside of a non-
356            // existent associated type, like `impl Trait<Missing = impl Trait>`.
357            // See <tests/ui/impl-trait/stranded-opaque.rs>.
358            let ty_err = ty_err.to_string(tcx);
359            let guar = tcx.dcx().span_delayed_bug(
360                span,
361                format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
362            );
363            return Err(guar);
364        }
365    }
366
367    // Additionally require the hidden type to be well-formed with only the generics of the opaque type.
368    // Defining use functions may have more bounds than the opaque type, which is ok, as long as the
369    // hidden type is well formed even without those bounds.
370    let predicate =
371        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(hidden_ty.into())));
372    ocx.register_obligation(Obligation::new(tcx, misc_cause.clone(), param_env, predicate));
373
374    // Check that all obligations are satisfied by the implementation's
375    // version.
376    let errors = ocx.evaluate_obligations_error_on_ambiguity();
377    if !errors.is_empty() {
378        let guar = infcx.err_ctxt().report_fulfillment_errors(errors);
379        return Err(guar);
380    }
381
382    let wf_tys = ocx.assumed_wf_types_and_report_errors(param_env, defining_use_anchor)?;
383    ocx.resolve_regions_and_report_errors(defining_use_anchor, param_env, wf_tys)?;
384
385    if infcx.next_trait_solver() {
386        Ok(())
387    } else if let hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } =
388        origin
389    {
390        // HACK: this should also fall through to the hidden type check below, but the original
391        // implementation had a bug where equivalent lifetimes are not identical. This caused us
392        // to reject existing stable code that is otherwise completely fine. The real fix is to
393        // compare the hidden types via our type equivalence/relation infra instead of doing an
394        // identity check.
395        let _ = infcx.take_opaque_types();
396        Ok(())
397    } else {
398        // Check that any hidden types found during wf checking match the hidden types that `type_of` sees.
399        for (mut key, mut ty) in infcx.take_opaque_types() {
400            ty.ty = infcx.resolve_vars_if_possible(ty.ty);
401            key = infcx.resolve_vars_if_possible(key);
402            sanity_check_found_hidden_type(tcx, key, ty)?;
403        }
404        Ok(())
405    }
406}
407
408fn best_definition_site_of_opaque<'tcx>(
409    tcx: TyCtxt<'tcx>,
410    opaque_def_id: LocalDefId,
411    origin: hir::OpaqueTyOrigin<LocalDefId>,
412) -> Option<(Span, LocalDefId)> {
413    struct TaitConstraintLocator<'tcx> {
414        opaque_def_id: LocalDefId,
415        tcx: TyCtxt<'tcx>,
416    }
417    impl<'tcx> TaitConstraintLocator<'tcx> {
418        fn check(&self, item_def_id: LocalDefId) -> ControlFlow<(Span, LocalDefId)> {
419            if !self.tcx.has_typeck_results(item_def_id) {
420                return ControlFlow::Continue(());
421            }
422
423            let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
424            // Don't try to check items that cannot possibly constrain the type.
425            if !opaque_types_defined_by.contains(&self.opaque_def_id) {
426                return ControlFlow::Continue(());
427            }
428
429            if let Some(hidden_ty) = self
430                .tcx
431                .mir_borrowck(item_def_id)
432                .ok()
433                .and_then(|opaque_types| opaque_types.get(&self.opaque_def_id))
434            {
435                ControlFlow::Break((hidden_ty.span, item_def_id))
436            } else {
437                ControlFlow::Continue(())
438            }
439        }
440    }
441    impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
442        type NestedFilter = nested_filter::All;
443        type Result = ControlFlow<(Span, LocalDefId)>;
444        fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
445            self.tcx
446        }
447        fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
448            intravisit::walk_expr(self, ex)
449        }
450        fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) -> Self::Result {
451            self.check(it.owner_id.def_id)?;
452            intravisit::walk_item(self, it)
453        }
454        fn visit_impl_item(&mut self, it: &'tcx hir::ImplItem<'tcx>) -> Self::Result {
455            self.check(it.owner_id.def_id)?;
456            intravisit::walk_impl_item(self, it)
457        }
458        fn visit_trait_item(&mut self, it: &'tcx hir::TraitItem<'tcx>) -> Self::Result {
459            self.check(it.owner_id.def_id)?;
460            intravisit::walk_trait_item(self, it)
461        }
462        fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) -> Self::Result {
463            intravisit::walk_foreign_item(self, it)
464        }
465    }
466
467    let mut locator = TaitConstraintLocator { tcx, opaque_def_id };
468    match origin {
469        hir::OpaqueTyOrigin::FnReturn { parent, .. }
470        | hir::OpaqueTyOrigin::AsyncFn { parent, .. } => locator.check(parent).break_value(),
471        hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty: true } => {
472            let impl_def_id = tcx.local_parent(parent);
473            for assoc in tcx.associated_items(impl_def_id).in_definition_order() {
474                match assoc.kind {
475                    ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => {
476                        if let ControlFlow::Break(span) = locator.check(assoc.def_id.expect_local())
477                        {
478                            return Some(span);
479                        }
480                    }
481                    ty::AssocKind::Type { .. } => {}
482                }
483            }
484
485            None
486        }
487        hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
488            tcx.hir_walk_toplevel_module(&mut locator).break_value()
489        }
490    }
491}
492
493fn sanity_check_found_hidden_type<'tcx>(
494    tcx: TyCtxt<'tcx>,
495    key: ty::OpaqueTypeKey<'tcx>,
496    mut ty: ty::ProvisionalHiddenType<'tcx>,
497) -> Result<(), ErrorGuaranteed> {
498    if ty.ty.is_ty_var() {
499        // Nothing was actually constrained.
500        return Ok(());
501    }
502    if let ty::Alias(ty::Opaque, alias) = ty.ty.kind() {
503        if alias.def_id == key.def_id.to_def_id() && alias.args == key.args {
504            // Nothing was actually constrained, this is an opaque usage that was
505            // only discovered to be opaque after inference vars resolved.
506            return Ok(());
507        }
508    }
509    let strip_vars = |ty: Ty<'tcx>| {
510        ty.fold_with(&mut BottomUpFolder {
511            tcx,
512            ty_op: |t| t,
513            ct_op: |c| c,
514            lt_op: |l| match l.kind() {
515                RegionKind::ReVar(_) => tcx.lifetimes.re_erased,
516                _ => l,
517            },
518        })
519    };
520    // Closures frequently end up containing erased lifetimes in their final representation.
521    // These correspond to lifetime variables that never got resolved, so we patch this up here.
522    ty.ty = strip_vars(ty.ty);
523    // Get the hidden type.
524    let hidden_ty = tcx.type_of(key.def_id).instantiate(tcx, key.args);
525    let hidden_ty = strip_vars(hidden_ty);
526
527    // If the hidden types differ, emit a type mismatch diagnostic.
528    if hidden_ty == ty.ty {
529        Ok(())
530    } else {
531        let span = tcx.def_span(key.def_id);
532        let other = ty::ProvisionalHiddenType { ty: hidden_ty, span };
533        Err(ty.build_mismatch_error(&other, tcx)?.emit())
534    }
535}
536
537/// Check that the opaque's precise captures list is valid (if present).
538/// We check this for regular `impl Trait`s and also RPITITs, even though the latter
539/// are technically GATs.
540///
541/// This function is responsible for:
542/// 1. Checking that all type/const params are mention in the captures list.
543/// 2. Checking that all lifetimes that are implicitly captured are mentioned.
544/// 3. Asserting that all parameters mentioned in the captures list are invariant.
545fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId) {
546    let hir::OpaqueTy { bounds, .. } = *tcx.hir_node_by_def_id(opaque_def_id).expect_opaque_ty();
547    let Some(precise_capturing_args) = bounds.iter().find_map(|bound| match *bound {
548        hir::GenericBound::Use(bounds, ..) => Some(bounds),
549        _ => None,
550    }) else {
551        // No precise capturing args; nothing to validate
552        return;
553    };
554
555    let mut expected_captures = UnordSet::default();
556    let mut shadowed_captures = UnordSet::default();
557    let mut seen_params = UnordMap::default();
558    let mut prev_non_lifetime_param = None;
559    for arg in precise_capturing_args {
560        let (hir_id, ident) = match *arg {
561            hir::PreciseCapturingArg::Param(hir::PreciseCapturingNonLifetimeArg {
562                hir_id,
563                ident,
564                ..
565            }) => {
566                if prev_non_lifetime_param.is_none() {
567                    prev_non_lifetime_param = Some(ident);
568                }
569                (hir_id, ident)
570            }
571            hir::PreciseCapturingArg::Lifetime(&hir::Lifetime { hir_id, ident, .. }) => {
572                if let Some(prev_non_lifetime_param) = prev_non_lifetime_param {
573                    tcx.dcx().emit_err(errors::LifetimesMustBeFirst {
574                        lifetime_span: ident.span,
575                        name: ident.name,
576                        other_span: prev_non_lifetime_param.span,
577                    });
578                }
579                (hir_id, ident)
580            }
581        };
582
583        let ident = ident.normalize_to_macros_2_0();
584        if let Some(span) = seen_params.insert(ident, ident.span) {
585            tcx.dcx().emit_err(errors::DuplicatePreciseCapture {
586                name: ident.name,
587                first_span: span,
588                second_span: ident.span,
589            });
590        }
591
592        match tcx.named_bound_var(hir_id) {
593            Some(ResolvedArg::EarlyBound(def_id)) => {
594                expected_captures.insert(def_id.to_def_id());
595
596                // Make sure we allow capturing these lifetimes through `Self` and
597                // `T::Assoc` projection syntax, too. These will occur when we only
598                // see lifetimes are captured after hir-lowering -- this aligns with
599                // the cases that were stabilized with the `impl_trait_projection`
600                // feature -- see <https://github.com/rust-lang/rust/pull/115659>.
601                if let DefKind::LifetimeParam = tcx.def_kind(def_id)
602                    && let Some(def_id) = tcx
603                        .map_opaque_lifetime_to_parent_lifetime(def_id)
604                        .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
605                {
606                    shadowed_captures.insert(def_id);
607                }
608            }
609            _ => {
610                tcx.dcx()
611                    .span_delayed_bug(tcx.hir_span(hir_id), "parameter should have been resolved");
612            }
613        }
614    }
615
616    let variances = tcx.variances_of(opaque_def_id);
617    let mut def_id = Some(opaque_def_id.to_def_id());
618    while let Some(generics) = def_id {
619        let generics = tcx.generics_of(generics);
620        def_id = generics.parent;
621
622        for param in &generics.own_params {
623            if expected_captures.contains(&param.def_id) {
624                assert_eq!(
625                    variances[param.index as usize],
626                    ty::Invariant,
627                    "precise captured param should be invariant"
628                );
629                continue;
630            }
631            // If a param is shadowed by a early-bound (duplicated) lifetime, then
632            // it may or may not be captured as invariant, depending on if it shows
633            // up through `Self` or `T::Assoc` syntax.
634            if shadowed_captures.contains(&param.def_id) {
635                continue;
636            }
637
638            match param.kind {
639                ty::GenericParamDefKind::Lifetime => {
640                    let use_span = tcx.def_span(param.def_id);
641                    let opaque_span = tcx.def_span(opaque_def_id);
642                    // Check if the lifetime param was captured but isn't named in the precise captures list.
643                    if variances[param.index as usize] == ty::Invariant {
644                        if let DefKind::OpaqueTy = tcx.def_kind(tcx.parent(param.def_id))
645                            && let Some(def_id) = tcx
646                                .map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local())
647                                .opt_param_def_id(tcx, tcx.parent(opaque_def_id.to_def_id()))
648                        {
649                            tcx.dcx().emit_err(errors::LifetimeNotCaptured {
650                                opaque_span,
651                                use_span,
652                                param_span: tcx.def_span(def_id),
653                            });
654                        } else {
655                            if tcx.def_kind(tcx.parent(param.def_id)) == DefKind::Trait {
656                                tcx.dcx().emit_err(errors::LifetimeImplicitlyCaptured {
657                                    opaque_span,
658                                    param_span: tcx.def_span(param.def_id),
659                                });
660                            } else {
661                                // If the `use_span` is actually just the param itself, then we must
662                                // have not duplicated the lifetime but captured the original.
663                                // The "effective" `use_span` will be the span of the opaque itself,
664                                // and the param span will be the def span of the param.
665                                tcx.dcx().emit_err(errors::LifetimeNotCaptured {
666                                    opaque_span,
667                                    use_span: opaque_span,
668                                    param_span: use_span,
669                                });
670                            }
671                        }
672                        continue;
673                    }
674                }
675                ty::GenericParamDefKind::Type { .. } => {
676                    if matches!(tcx.def_kind(param.def_id), DefKind::Trait | DefKind::TraitAlias) {
677                        // FIXME(precise_capturing): Structured suggestion for this would be useful
678                        tcx.dcx().emit_err(errors::SelfTyNotCaptured {
679                            trait_span: tcx.def_span(param.def_id),
680                            opaque_span: tcx.def_span(opaque_def_id),
681                        });
682                    } else {
683                        // FIXME(precise_capturing): Structured suggestion for this would be useful
684                        tcx.dcx().emit_err(errors::ParamNotCaptured {
685                            param_span: tcx.def_span(param.def_id),
686                            opaque_span: tcx.def_span(opaque_def_id),
687                            kind: "type",
688                        });
689                    }
690                }
691                ty::GenericParamDefKind::Const { .. } => {
692                    // FIXME(precise_capturing): Structured suggestion for this would be useful
693                    tcx.dcx().emit_err(errors::ParamNotCaptured {
694                        param_span: tcx.def_span(param.def_id),
695                        opaque_span: tcx.def_span(opaque_def_id),
696                        kind: "const",
697                    });
698                }
699            }
700        }
701    }
702}
703
704fn is_enum_of_nonnullable_ptr<'tcx>(
705    tcx: TyCtxt<'tcx>,
706    adt_def: AdtDef<'tcx>,
707    args: GenericArgsRef<'tcx>,
708) -> bool {
709    if adt_def.repr().inhibit_enum_layout_opt() {
710        return false;
711    }
712
713    let [var_one, var_two] = &adt_def.variants().raw[..] else {
714        return false;
715    };
716    let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else {
717        return false;
718    };
719    matches!(field.ty(tcx, args).kind(), ty::FnPtr(..) | ty::Ref(..))
720}
721
722fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) {
723    if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() {
724        if match tcx.type_of(def_id).instantiate_identity().kind() {
725            ty::RawPtr(_, _) => false,
726            ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args),
727            _ => true,
728        } {
729            tcx.dcx().emit_err(errors::LinkageType { span: tcx.def_span(def_id) });
730        }
731    }
732}
733
734pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
735    let mut res = Ok(());
736    let generics = tcx.generics_of(def_id);
737
738    for param in &generics.own_params {
739        match param.kind {
740            ty::GenericParamDefKind::Lifetime { .. } => {}
741            ty::GenericParamDefKind::Type { has_default, .. } => {
742                if has_default {
743                    tcx.ensure_ok().type_of(param.def_id);
744                }
745            }
746            ty::GenericParamDefKind::Const { has_default, .. } => {
747                tcx.ensure_ok().type_of(param.def_id);
748                if has_default {
749                    // need to store default and type of default
750                    let ct = tcx.const_param_default(param.def_id).skip_binder();
751                    if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
752                        tcx.ensure_ok().type_of(uv.def);
753                    }
754                }
755            }
756        }
757    }
758
759    match tcx.def_kind(def_id) {
760        DefKind::Static { .. } => {
761            tcx.ensure_ok().generics_of(def_id);
762            tcx.ensure_ok().type_of(def_id);
763            tcx.ensure_ok().predicates_of(def_id);
764
765            check_static_inhabited(tcx, def_id);
766            check_static_linkage(tcx, def_id);
767            let ty = tcx.type_of(def_id).instantiate_identity();
768            res = res.and(wfcheck::check_static_item(
769                tcx, def_id, ty, /* should_check_for_sync */ true,
770            ));
771
772            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
773            // checks. Returning early here does not miss any checks and
774            // avoids this query from having a direct dependency edge on the HIR
775            return res;
776        }
777        DefKind::Enum => {
778            tcx.ensure_ok().generics_of(def_id);
779            tcx.ensure_ok().type_of(def_id);
780            tcx.ensure_ok().predicates_of(def_id);
781            crate::collect::lower_enum_variant_types(tcx, def_id);
782            check_enum(tcx, def_id);
783            check_variances_for_type_defn(tcx, def_id);
784        }
785        DefKind::Fn => {
786            tcx.ensure_ok().generics_of(def_id);
787            tcx.ensure_ok().type_of(def_id);
788            tcx.ensure_ok().predicates_of(def_id);
789            tcx.ensure_ok().fn_sig(def_id);
790            tcx.ensure_ok().codegen_fn_attrs(def_id);
791            if let Some(i) = tcx.intrinsic(def_id) {
792                intrinsic::check_intrinsic_type(
793                    tcx,
794                    def_id,
795                    tcx.def_ident_span(def_id).unwrap(),
796                    i.name,
797                )
798            }
799        }
800        DefKind::Impl { of_trait } => {
801            tcx.ensure_ok().generics_of(def_id);
802            tcx.ensure_ok().type_of(def_id);
803            tcx.ensure_ok().predicates_of(def_id);
804            tcx.ensure_ok().associated_items(def_id);
805            if of_trait {
806                let impl_trait_header = tcx.impl_trait_header(def_id);
807                res = res.and(
808                    tcx.ensure_ok()
809                        .coherent_trait(impl_trait_header.trait_ref.instantiate_identity().def_id),
810                );
811
812                if res.is_ok() {
813                    // Checking this only makes sense if the all trait impls satisfy basic
814                    // requirements (see `coherent_trait` query), otherwise
815                    // we run into infinite recursions a lot.
816                    check_impl_items_against_trait(tcx, def_id, impl_trait_header);
817                }
818            }
819        }
820        DefKind::Trait => {
821            tcx.ensure_ok().generics_of(def_id);
822            tcx.ensure_ok().trait_def(def_id);
823            tcx.ensure_ok().explicit_super_predicates_of(def_id);
824            tcx.ensure_ok().predicates_of(def_id);
825            tcx.ensure_ok().associated_items(def_id);
826            let assoc_items = tcx.associated_items(def_id);
827            check_on_unimplemented(tcx, def_id);
828
829            for &assoc_item in assoc_items.in_definition_order() {
830                match assoc_item.kind {
831                    ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => {
832                        let trait_args = GenericArgs::identity_for_item(tcx, def_id);
833                        let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds(
834                            tcx,
835                            assoc_item,
836                            assoc_item,
837                            ty::TraitRef::new_from_args(tcx, def_id.to_def_id(), trait_args),
838                        );
839                    }
840                    _ => {}
841                }
842            }
843        }
844        DefKind::TraitAlias => {
845            tcx.ensure_ok().generics_of(def_id);
846            tcx.ensure_ok().explicit_implied_predicates_of(def_id);
847            tcx.ensure_ok().explicit_super_predicates_of(def_id);
848            tcx.ensure_ok().predicates_of(def_id);
849        }
850        def_kind @ (DefKind::Struct | DefKind::Union) => {
851            tcx.ensure_ok().generics_of(def_id);
852            tcx.ensure_ok().type_of(def_id);
853            tcx.ensure_ok().predicates_of(def_id);
854
855            let adt = tcx.adt_def(def_id).non_enum_variant();
856            for f in adt.fields.iter() {
857                tcx.ensure_ok().generics_of(f.did);
858                tcx.ensure_ok().type_of(f.did);
859                tcx.ensure_ok().predicates_of(f.did);
860            }
861
862            if let Some((_, ctor_def_id)) = adt.ctor {
863                crate::collect::lower_variant_ctor(tcx, ctor_def_id.expect_local());
864            }
865            match def_kind {
866                DefKind::Struct => check_struct(tcx, def_id),
867                DefKind::Union => check_union(tcx, def_id),
868                _ => unreachable!(),
869            }
870            check_variances_for_type_defn(tcx, def_id);
871        }
872        DefKind::OpaqueTy => {
873            check_opaque_precise_captures(tcx, def_id);
874
875            let origin = tcx.local_opaque_ty_origin(def_id);
876            if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
877            | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } = origin
878                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
879                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
880            {
881                // Skip opaques from RPIT in traits with no default body.
882            } else {
883                check_opaque(tcx, def_id);
884            }
885
886            tcx.ensure_ok().predicates_of(def_id);
887            tcx.ensure_ok().explicit_item_bounds(def_id);
888            tcx.ensure_ok().explicit_item_self_bounds(def_id);
889            if tcx.is_conditionally_const(def_id) {
890                tcx.ensure_ok().explicit_implied_const_bounds(def_id);
891                tcx.ensure_ok().const_conditions(def_id);
892            }
893
894            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
895            // checks. Returning early here does not miss any checks and
896            // avoids this query from having a direct dependency edge on the HIR
897            return res;
898        }
899        DefKind::Const => {
900            tcx.ensure_ok().generics_of(def_id);
901            tcx.ensure_ok().type_of(def_id);
902            tcx.ensure_ok().predicates_of(def_id);
903
904            res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
905                let ty = tcx.type_of(def_id).instantiate_identity();
906                let ty_span = tcx.ty_span(def_id);
907                let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
908                wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
909                wfcx.register_bound(
910                    traits::ObligationCause::new(
911                        ty_span,
912                        def_id,
913                        ObligationCauseCode::SizedConstOrStatic,
914                    ),
915                    tcx.param_env(def_id),
916                    ty,
917                    tcx.require_lang_item(LangItem::Sized, ty_span),
918                );
919                check_where_clauses(wfcx, def_id);
920
921                if find_attr!(tcx.get_all_attrs(def_id), AttributeKind::TypeConst(_)) {
922                    wfcheck::check_type_const(wfcx, def_id, ty, true)?;
923                }
924                Ok(())
925            }));
926
927            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
928            // checks. Returning early here does not miss any checks and
929            // avoids this query from having a direct dependency edge on the HIR
930            return res;
931        }
932        DefKind::TyAlias => {
933            tcx.ensure_ok().generics_of(def_id);
934            tcx.ensure_ok().type_of(def_id);
935            tcx.ensure_ok().predicates_of(def_id);
936            check_type_alias_type_params_are_used(tcx, def_id);
937            if tcx.type_alias_is_lazy(def_id) {
938                res = res.and(enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
939                    let ty = tcx.type_of(def_id).instantiate_identity();
940                    let span = tcx.def_span(def_id);
941                    let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), ty);
942                    wfcx.register_wf_obligation(
943                        span,
944                        Some(WellFormedLoc::Ty(def_id)),
945                        item_ty.into(),
946                    );
947                    check_where_clauses(wfcx, def_id);
948                    Ok(())
949                }));
950                check_variances_for_type_defn(tcx, def_id);
951            }
952
953            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
954            // checks. Returning early here does not miss any checks and
955            // avoids this query from having a direct dependency edge on the HIR
956            return res;
957        }
958        DefKind::ForeignMod => {
959            let it = tcx.hir_expect_item(def_id);
960            let hir::ItemKind::ForeignMod { abi, items } = it.kind else {
961                return Ok(());
962            };
963
964            check_abi(tcx, it.hir_id(), it.span, abi);
965
966            for &item in items {
967                let def_id = item.owner_id.def_id;
968
969                let generics = tcx.generics_of(def_id);
970                let own_counts = generics.own_counts();
971                if generics.own_params.len() - own_counts.lifetimes != 0 {
972                    let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) {
973                        (_, 0) => ("type", "types", Some("u32")),
974                        // We don't specify an example value, because we can't generate
975                        // a valid value for any type.
976                        (0, _) => ("const", "consts", None),
977                        _ => ("type or const", "types or consts", None),
978                    };
979                    let span = tcx.def_span(def_id);
980                    struct_span_code_err!(
981                        tcx.dcx(),
982                        span,
983                        E0044,
984                        "foreign items may not have {kinds} parameters",
985                    )
986                    .with_span_label(span, format!("can't have {kinds} parameters"))
987                    .with_help(
988                        // FIXME: once we start storing spans for type arguments, turn this
989                        // into a suggestion.
990                        format!(
991                            "replace the {} parameters with concrete {}{}",
992                            kinds,
993                            kinds_pl,
994                            egs.map(|egs| format!(" like `{egs}`")).unwrap_or_default(),
995                        ),
996                    )
997                    .emit();
998                }
999
1000                tcx.ensure_ok().generics_of(def_id);
1001                tcx.ensure_ok().type_of(def_id);
1002                tcx.ensure_ok().predicates_of(def_id);
1003                if tcx.is_conditionally_const(def_id) {
1004                    tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1005                    tcx.ensure_ok().const_conditions(def_id);
1006                }
1007                match tcx.def_kind(def_id) {
1008                    DefKind::Fn => {
1009                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1010                        tcx.ensure_ok().fn_sig(def_id);
1011                        let item = tcx.hir_foreign_item(item);
1012                        let hir::ForeignItemKind::Fn(sig, ..) = item.kind else { bug!() };
1013                        check_c_variadic_abi(tcx, sig.decl, abi, item.span);
1014                    }
1015                    DefKind::Static { .. } => {
1016                        tcx.ensure_ok().codegen_fn_attrs(def_id);
1017                    }
1018                    _ => (),
1019                }
1020            }
1021        }
1022        DefKind::Closure => {
1023            // This is guaranteed to be called by metadata encoding,
1024            // we still call it in wfcheck eagerly to ensure errors in codegen
1025            // attrs prevent lints from spamming the output.
1026            tcx.ensure_ok().codegen_fn_attrs(def_id);
1027            // We do not call `type_of` for closures here as that
1028            // depends on typecheck and would therefore hide
1029            // any further errors in case one typeck fails.
1030
1031            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1032            // checks. Returning early here does not miss any checks and
1033            // avoids this query from having a direct dependency edge on the HIR
1034            return res;
1035        }
1036        DefKind::AssocFn => {
1037            tcx.ensure_ok().codegen_fn_attrs(def_id);
1038            tcx.ensure_ok().type_of(def_id);
1039            tcx.ensure_ok().fn_sig(def_id);
1040            tcx.ensure_ok().predicates_of(def_id);
1041            res = res.and(check_associated_item(tcx, def_id));
1042            let assoc_item = tcx.associated_item(def_id);
1043            match assoc_item.container {
1044                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1045                ty::AssocContainer::Trait => {
1046                    res = res.and(check_trait_item(tcx, def_id));
1047                }
1048            }
1049
1050            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1051            // checks. Returning early here does not miss any checks and
1052            // avoids this query from having a direct dependency edge on the HIR
1053            return res;
1054        }
1055        DefKind::AssocConst => {
1056            tcx.ensure_ok().type_of(def_id);
1057            tcx.ensure_ok().predicates_of(def_id);
1058            res = res.and(check_associated_item(tcx, def_id));
1059            let assoc_item = tcx.associated_item(def_id);
1060            match assoc_item.container {
1061                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1062                ty::AssocContainer::Trait => {
1063                    res = res.and(check_trait_item(tcx, def_id));
1064                }
1065            }
1066
1067            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1068            // checks. Returning early here does not miss any checks and
1069            // avoids this query from having a direct dependency edge on the HIR
1070            return res;
1071        }
1072        DefKind::AssocTy => {
1073            tcx.ensure_ok().predicates_of(def_id);
1074            res = res.and(check_associated_item(tcx, def_id));
1075
1076            let assoc_item = tcx.associated_item(def_id);
1077            let has_type = match assoc_item.container {
1078                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1079                ty::AssocContainer::Trait => {
1080                    tcx.ensure_ok().explicit_item_bounds(def_id);
1081                    tcx.ensure_ok().explicit_item_self_bounds(def_id);
1082                    if tcx.is_conditionally_const(def_id) {
1083                        tcx.ensure_ok().explicit_implied_const_bounds(def_id);
1084                        tcx.ensure_ok().const_conditions(def_id);
1085                    }
1086                    res = res.and(check_trait_item(tcx, def_id));
1087                    assoc_item.defaultness(tcx).has_value()
1088                }
1089            };
1090            if has_type {
1091                tcx.ensure_ok().type_of(def_id);
1092            }
1093
1094            // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1095            // checks. Returning early here does not miss any checks and
1096            // avoids this query from having a direct dependency edge on the HIR
1097            return res;
1098        }
1099
1100        // Only `Node::Item` and `Node::ForeignItem` still have HIR based
1101        // checks. Returning early here does not miss any checks and
1102        // avoids this query from having a direct dependency edge on the HIR
1103        DefKind::AnonConst | DefKind::InlineConst => return res,
1104        _ => {}
1105    }
1106    let node = tcx.hir_node_by_def_id(def_id);
1107    res.and(match node {
1108        hir::Node::Crate(_) => bug!("check_well_formed cannot be applied to the crate root"),
1109        hir::Node::Item(item) => wfcheck::check_item(tcx, item),
1110        hir::Node::ForeignItem(item) => wfcheck::check_foreign_item(tcx, item),
1111        _ => unreachable!("{node:?}"),
1112    })
1113}
1114
1115pub(super) fn check_on_unimplemented(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1116    // an error would be reported if this fails.
1117    let _ = OnUnimplementedDirective::of_item(tcx, def_id.to_def_id());
1118}
1119
1120pub(super) fn check_specialization_validity<'tcx>(
1121    tcx: TyCtxt<'tcx>,
1122    trait_def: &ty::TraitDef,
1123    trait_item: ty::AssocItem,
1124    impl_id: DefId,
1125    impl_item: DefId,
1126) {
1127    let Ok(ancestors) = trait_def.ancestors(tcx, impl_id) else { return };
1128    let mut ancestor_impls = ancestors.skip(1).filter_map(|parent| {
1129        if parent.is_from_trait() {
1130            None
1131        } else {
1132            Some((parent, parent.item(tcx, trait_item.def_id)))
1133        }
1134    });
1135
1136    let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1137        match parent_item {
1138            // Parent impl exists, and contains the parent item we're trying to specialize, but
1139            // doesn't mark it `default`.
1140            Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => {
1141                Some(Err(parent_impl.def_id()))
1142            }
1143
1144            // Parent impl contains item and makes it specializable.
1145            Some(_) => Some(Ok(())),
1146
1147            // Parent impl doesn't mention the item. This means it's inherited from the
1148            // grandparent. In that case, if parent is a `default impl`, inherited items use the
1149            // "defaultness" from the grandparent, else they are final.
1150            None => {
1151                if tcx.defaultness(parent_impl.def_id()).is_default() {
1152                    None
1153                } else {
1154                    Some(Err(parent_impl.def_id()))
1155                }
1156            }
1157        }
1158    });
1159
1160    // If `opt_result` is `None`, we have only encountered `default impl`s that don't contain the
1161    // item. This is allowed, the item isn't actually getting specialized here.
1162    let result = opt_result.unwrap_or(Ok(()));
1163
1164    if let Err(parent_impl) = result {
1165        if !tcx.is_impl_trait_in_trait(impl_item) {
1166            report_forbidden_specialization(tcx, impl_item, parent_impl);
1167        } else {
1168            tcx.dcx().delayed_bug(format!("parent item: {parent_impl:?} not marked as default"));
1169        }
1170    }
1171}
1172
1173fn check_impl_items_against_trait<'tcx>(
1174    tcx: TyCtxt<'tcx>,
1175    impl_id: LocalDefId,
1176    impl_trait_header: ty::ImplTraitHeader<'tcx>,
1177) {
1178    let trait_ref = impl_trait_header.trait_ref.instantiate_identity();
1179    // If the trait reference itself is erroneous (so the compilation is going
1180    // to fail), skip checking the items here -- the `impl_item` table in `tcx`
1181    // isn't populated for such impls.
1182    if trait_ref.references_error() {
1183        return;
1184    }
1185
1186    let impl_item_refs = tcx.associated_item_def_ids(impl_id);
1187
1188    // Negative impls are not expected to have any items
1189    match impl_trait_header.polarity {
1190        ty::ImplPolarity::Reservation | ty::ImplPolarity::Positive => {}
1191        ty::ImplPolarity::Negative => {
1192            if let [first_item_ref, ..] = impl_item_refs {
1193                let first_item_span = tcx.def_span(first_item_ref);
1194                struct_span_code_err!(
1195                    tcx.dcx(),
1196                    first_item_span,
1197                    E0749,
1198                    "negative impls cannot have any items"
1199                )
1200                .emit();
1201            }
1202            return;
1203        }
1204    }
1205
1206    let trait_def = tcx.trait_def(trait_ref.def_id);
1207
1208    let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
1209
1210    for &impl_item in impl_item_refs {
1211        let ty_impl_item = tcx.associated_item(impl_item);
1212        let ty_trait_item = match ty_impl_item.expect_trait_impl() {
1213            Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1214            Err(ErrorGuaranteed { .. }) => continue,
1215        };
1216
1217        let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
1218
1219        if res.is_ok() {
1220            match ty_impl_item.kind {
1221                ty::AssocKind::Fn { .. } => {
1222                    compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1223                        tcx,
1224                        ty_impl_item,
1225                        ty_trait_item,
1226                        tcx.impl_trait_ref(ty_impl_item.container_id(tcx)).instantiate_identity(),
1227                    );
1228                }
1229                ty::AssocKind::Const { .. } => {}
1230                ty::AssocKind::Type { .. } => {}
1231            }
1232        }
1233
1234        if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1235            tcx.emit_node_span_lint(
1236                rustc_lint_defs::builtin::DEAD_CODE,
1237                tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1238                tcx.def_span(ty_impl_item.def_id),
1239                errors::UselessImplItem,
1240            )
1241        }
1242
1243        check_specialization_validity(
1244            tcx,
1245            trait_def,
1246            ty_trait_item,
1247            impl_id.to_def_id(),
1248            impl_item,
1249        );
1250    }
1251
1252    if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1253        // Check for missing items from trait
1254        let mut missing_items = Vec::new();
1255
1256        let mut must_implement_one_of: Option<&[Ident]> =
1257            trait_def.must_implement_one_of.as_deref();
1258
1259        for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1260            let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1261
1262            let is_implemented = leaf_def
1263                .as_ref()
1264                .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1265
1266            if !is_implemented
1267                && tcx.defaultness(impl_id).is_final()
1268                // unsized types don't need to implement methods that have `Self: Sized` bounds.
1269                && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1270            {
1271                missing_items.push(tcx.associated_item(trait_item_id));
1272            }
1273
1274            // true if this item is specifically implemented in this impl
1275            let is_implemented_here =
1276                leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1277
1278            if !is_implemented_here {
1279                let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1280                match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1281                    EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1282                        tcx,
1283                        full_impl_span,
1284                        trait_item_id,
1285                        feature,
1286                        reason,
1287                        issue,
1288                    ),
1289
1290                    // Unmarked default bodies are considered stable (at least for now).
1291                    EvalResult::Allow | EvalResult::Unmarked => {}
1292                }
1293            }
1294
1295            if let Some(required_items) = &must_implement_one_of {
1296                if is_implemented_here {
1297                    let trait_item = tcx.associated_item(trait_item_id);
1298                    if required_items.contains(&trait_item.ident(tcx)) {
1299                        must_implement_one_of = None;
1300                    }
1301                }
1302            }
1303
1304            if let Some(leaf_def) = &leaf_def
1305                && !leaf_def.is_final()
1306                && let def_id = leaf_def.item.def_id
1307                && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1308            {
1309                let def_kind = tcx.def_kind(def_id);
1310                let descr = tcx.def_kind_descr(def_kind, def_id);
1311                let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1312                    (
1313                        format!("async {descr} in trait cannot be specialized"),
1314                        "async functions in traits",
1315                    )
1316                } else {
1317                    (
1318                        format!(
1319                            "{descr} with return-position `impl Trait` in trait cannot be specialized"
1320                        ),
1321                        "return position `impl Trait` in traits",
1322                    )
1323                };
1324                tcx.dcx()
1325                    .struct_span_err(tcx.def_span(def_id), msg)
1326                    .with_note(format!(
1327                        "specialization behaves in inconsistent and surprising ways with \
1328                        {feature}, and for now is disallowed"
1329                    ))
1330                    .emit();
1331            }
1332        }
1333
1334        if !missing_items.is_empty() {
1335            let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1336            missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1337        }
1338
1339        if let Some(missing_items) = must_implement_one_of {
1340            let attr_span = tcx
1341                .get_attr(trait_ref.def_id, sym::rustc_must_implement_one_of)
1342                .map(|attr| attr.span());
1343
1344            missing_items_must_implement_one_of_err(
1345                tcx,
1346                tcx.def_span(impl_id),
1347                missing_items,
1348                attr_span,
1349            );
1350        }
1351    }
1352}
1353
1354fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1355    let t = tcx.type_of(def_id).instantiate_identity();
1356    if let ty::Adt(def, args) = t.kind()
1357        && def.is_struct()
1358    {
1359        let fields = &def.non_enum_variant().fields;
1360        if fields.is_empty() {
1361            struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1362            return;
1363        }
1364
1365        let array_field = &fields[FieldIdx::ZERO];
1366        let array_ty = array_field.ty(tcx, args);
1367        let ty::Array(element_ty, len_const) = array_ty.kind() else {
1368            struct_span_code_err!(
1369                tcx.dcx(),
1370                sp,
1371                E0076,
1372                "SIMD vector's only field must be an array"
1373            )
1374            .with_span_label(tcx.def_span(array_field.did), "not an array")
1375            .emit();
1376            return;
1377        };
1378
1379        if let Some(second_field) = fields.get(FieldIdx::ONE) {
1380            struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1381                .with_span_label(tcx.def_span(second_field.did), "excess field")
1382                .emit();
1383            return;
1384        }
1385
1386        // FIXME(repr_simd): This check is nice, but perhaps unnecessary due to the fact
1387        // we do not expect users to implement their own `repr(simd)` types. If they could,
1388        // this check is easily side-steppable by hiding the const behind normalization.
1389        // The consequence is that the error is, in general, only observable post-mono.
1390        if let Some(len) = len_const.try_to_target_usize(tcx) {
1391            if len == 0 {
1392                struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1393                return;
1394            } else if len > MAX_SIMD_LANES {
1395                struct_span_code_err!(
1396                    tcx.dcx(),
1397                    sp,
1398                    E0075,
1399                    "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1400                )
1401                .emit();
1402                return;
1403            }
1404        }
1405
1406        // Check that we use types valid for use in the lanes of a SIMD "vector register"
1407        // These are scalar types which directly match a "machine" type
1408        // Yes: Integers, floats, "thin" pointers
1409        // No: char, "wide" pointers, compound types
1410        match element_ty.kind() {
1411            ty::Param(_) => (), // pass struct<T>([T; 4]) through, let monomorphization catch errors
1412            ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), // struct([u8; 4]) is ok
1413            _ => {
1414                struct_span_code_err!(
1415                    tcx.dcx(),
1416                    sp,
1417                    E0077,
1418                    "SIMD vector element type should be a \
1419                        primitive scalar (integer/float/pointer) type"
1420                )
1421                .emit();
1422                return;
1423            }
1424        }
1425    }
1426}
1427
1428pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1429    let repr = def.repr();
1430    if repr.packed() {
1431        if let Some(reprs) = find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs)
1432        {
1433            for (r, _) in reprs {
1434                if let ReprPacked(pack) = r
1435                    && let Some(repr_pack) = repr.pack
1436                    && pack != &repr_pack
1437                {
1438                    struct_span_code_err!(
1439                        tcx.dcx(),
1440                        sp,
1441                        E0634,
1442                        "type has conflicting packed representation hints"
1443                    )
1444                    .emit();
1445                }
1446            }
1447        }
1448        if repr.align.is_some() {
1449            struct_span_code_err!(
1450                tcx.dcx(),
1451                sp,
1452                E0587,
1453                "type has conflicting packed and align representation hints"
1454            )
1455            .emit();
1456        } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1457            let mut err = struct_span_code_err!(
1458                tcx.dcx(),
1459                sp,
1460                E0588,
1461                "packed type cannot transitively contain a `#[repr(align)]` type"
1462            );
1463
1464            err.span_note(
1465                tcx.def_span(def_spans[0].0),
1466                format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
1467            );
1468
1469            if def_spans.len() > 2 {
1470                let mut first = true;
1471                for (adt_def, span) in def_spans.iter().skip(1).rev() {
1472                    let ident = tcx.item_name(*adt_def);
1473                    err.span_note(
1474                        *span,
1475                        if first {
1476                            format!(
1477                                "`{}` contains a field of type `{}`",
1478                                tcx.type_of(def.did()).instantiate_identity(),
1479                                ident
1480                            )
1481                        } else {
1482                            format!("...which contains a field of type `{ident}`")
1483                        },
1484                    );
1485                    first = false;
1486                }
1487            }
1488
1489            err.emit();
1490        }
1491    }
1492}
1493
1494pub(super) fn check_packed_inner(
1495    tcx: TyCtxt<'_>,
1496    def_id: DefId,
1497    stack: &mut Vec<DefId>,
1498) -> Option<Vec<(DefId, Span)>> {
1499    if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1500        if def.is_struct() || def.is_union() {
1501            if def.repr().align.is_some() {
1502                return Some(vec![(def.did(), DUMMY_SP)]);
1503            }
1504
1505            stack.push(def_id);
1506            for field in &def.non_enum_variant().fields {
1507                if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1508                    && !stack.contains(&def.did())
1509                    && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1510                {
1511                    defs.push((def.did(), field.ident(tcx).span));
1512                    return Some(defs);
1513                }
1514            }
1515            stack.pop();
1516        }
1517    }
1518
1519    None
1520}
1521
1522pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1523    if !adt.repr().transparent() {
1524        return;
1525    }
1526
1527    if adt.is_union() && !tcx.features().transparent_unions() {
1528        feature_err(
1529            &tcx.sess,
1530            sym::transparent_unions,
1531            tcx.def_span(adt.did()),
1532            "transparent unions are unstable",
1533        )
1534        .emit();
1535    }
1536
1537    if adt.variants().len() != 1 {
1538        bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1539        // Don't bother checking the fields.
1540        return;
1541    }
1542
1543    let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
1544    // For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545    struct FieldInfo<'tcx> {
1546        span: Span,
1547        trivial: bool,
1548        ty: Ty<'tcx>,
1549    }
1550
1551    let field_infos = adt.all_fields().map(|field| {
1552        let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1553        let layout = tcx.layout_of(typing_env.as_query_input(ty));
1554        // We are currently checking the type this field came from, so it must be local
1555        let span = tcx.hir_span_if_local(field.did).unwrap();
1556        let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1557        FieldInfo { span, trivial, ty }
1558    });
1559
1560    let non_trivial_fields = field_infos
1561        .clone()
1562        .filter_map(|field| if !field.trivial { Some(field.span) } else { None });
1563    let non_trivial_count = non_trivial_fields.clone().count();
1564    if non_trivial_count >= 2 {
1565        bad_non_zero_sized_fields(
1566            tcx,
1567            adt,
1568            non_trivial_count,
1569            non_trivial_fields,
1570            tcx.def_span(adt.did()),
1571        );
1572        return;
1573    }
1574
1575    // Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576    // fields or `repr(C)`. We call those fields "unsuited".
1577    struct UnsuitedInfo<'tcx> {
1578        /// The source of the problem, a type that is found somewhere within the field type.
1579        ty: Ty<'tcx>,
1580        reason: UnsuitedReason,
1581    }
1582    enum UnsuitedReason {
1583        NonExhaustive,
1584        PrivateField,
1585        ReprC,
1586    }
1587
1588    fn check_unsuited<'tcx>(
1589        tcx: TyCtxt<'tcx>,
1590        typing_env: ty::TypingEnv<'tcx>,
1591        ty: Ty<'tcx>,
1592    ) -> ControlFlow<UnsuitedInfo<'tcx>> {
1593        // We can encounter projections during traversal, so ensure the type is normalized.
1594        let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595        match ty.kind() {
1596            ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597            ty::Array(ty, _) => check_unsuited(tcx, typing_env, *ty),
1598            ty::Adt(def, args) => {
1599                if !def.did().is_local()
1600                    && !find_attr!(tcx.get_all_attrs(def.did()), AttributeKind::PubTransparent(_))
1601                {
1602                    let non_exhaustive = def.is_variant_list_non_exhaustive()
1603                        || def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604                    let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605                    if non_exhaustive || has_priv {
1606                        return ControlFlow::Break(UnsuitedInfo {
1607                            ty,
1608                            reason: if non_exhaustive {
1609                                UnsuitedReason::NonExhaustive
1610                            } else {
1611                                UnsuitedReason::PrivateField
1612                            },
1613                        });
1614                    }
1615                }
1616                if def.repr().c() {
1617                    return ControlFlow::Break(UnsuitedInfo { ty, reason: UnsuitedReason::ReprC });
1618                }
1619                def.all_fields()
1620                    .map(|field| field.ty(tcx, args))
1621                    .try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622            }
1623            _ => ControlFlow::Continue(()),
1624        }
1625    }
1626
1627    let mut prev_unsuited_1zst = false;
1628    for field in field_infos {
1629        if field.trivial
1630            && let Some(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631        {
1632            // If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
1633            // Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
1634            if non_trivial_count > 0 || prev_unsuited_1zst {
1635                tcx.node_span_lint(
1636                    REPR_TRANSPARENT_NON_ZST_FIELDS,
1637                    tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1638                    field.span,
1639                    |lint| {
1640                        let title = match unsuited.reason {
1641                            UnsuitedReason::NonExhaustive => "external non-exhaustive types",
1642                            UnsuitedReason::PrivateField => "external types with private fields",
1643                            UnsuitedReason::ReprC => "`repr(C)` types",
1644                        };
1645                        lint.primary_message(
1646                            format!("zero-sized fields in `repr(transparent)` cannot contain {title}"),
1647                        );
1648                        let note = match unsuited.reason {
1649                            UnsuitedReason::NonExhaustive => "is marked with `#[non_exhaustive]`, so it could become non-zero-sized in the future.",
1650                            UnsuitedReason::PrivateField => "contains private fields, so it could become non-zero-sized in the future.",
1651                            UnsuitedReason::ReprC => "is a `#[repr(C)]` type, so it is not guaranteed to be zero-sized on all targets.",
1652                        };
1653                        lint.note(format!(
1654                            "this field contains `{field_ty}`, which {note}",
1655                            field_ty = unsuited.ty,
1656                        ));
1657                    },
1658                );
1659            } else {
1660                prev_unsuited_1zst = true;
1661            }
1662        }
1663    }
1664}
1665
1666#[allow(trivial_numeric_casts)]
1667fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1668    let def = tcx.adt_def(def_id);
1669    def.destructor(tcx); // force the destructor to be evaluated
1670
1671    if def.variants().is_empty() {
1672        find_attr!(
1673            tcx.get_all_attrs(def_id),
1674            attrs::AttributeKind::Repr { reprs, first_span } => {
1675                struct_span_code_err!(
1676                    tcx.dcx(),
1677                    reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1678                    E0084,
1679                    "unsupported representation for zero-variant enum"
1680                )
1681                .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1682                .emit();
1683            }
1684        );
1685    }
1686
1687    for v in def.variants() {
1688        if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1689            tcx.ensure_ok().typeck(discr_def_id.expect_local());
1690        }
1691    }
1692
1693    if def.repr().int.is_none() {
1694        let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1695        let get_disr = |var: &ty::VariantDef| match var.discr {
1696            ty::VariantDiscr::Explicit(disr) => Some(disr),
1697            ty::VariantDiscr::Relative(_) => None,
1698        };
1699
1700        let non_unit = def.variants().iter().find(|var| !is_unit(var));
1701        let disr_unit =
1702            def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1703        let disr_non_unit =
1704            def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1705
1706        if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1707            let mut err = struct_span_code_err!(
1708                tcx.dcx(),
1709                tcx.def_span(def_id),
1710                E0732,
1711                "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1712            );
1713            if let Some(disr_non_unit) = disr_non_unit {
1714                err.span_label(
1715                    tcx.def_span(disr_non_unit),
1716                    "explicit discriminant on non-unit variant specified here",
1717                );
1718            } else {
1719                err.span_label(
1720                    tcx.def_span(disr_unit.unwrap()),
1721                    "explicit discriminant specified here",
1722                );
1723                err.span_label(
1724                    tcx.def_span(non_unit.unwrap().def_id),
1725                    "non-unit discriminant declared here",
1726                );
1727            }
1728            err.emit();
1729        }
1730    }
1731
1732    detect_discriminant_duplicate(tcx, def);
1733    check_transparent(tcx, def);
1734}
1735
1736/// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1737fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1738    // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1739    // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1740    let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1741        let var = adt.variant(idx); // HIR for the duplicate discriminant
1742        let (span, display_discr) = match var.discr {
1743            ty::VariantDiscr::Explicit(discr_def_id) => {
1744                // In the case the discriminant is both a duplicate and overflowed, let the user know
1745                if let hir::Node::AnonConst(expr) =
1746                    tcx.hir_node_by_def_id(discr_def_id.expect_local())
1747                    && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1748                    && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1749                    && *lit_value != dis.val
1750                {
1751                    (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1752                } else {
1753                    // Otherwise, format the value as-is
1754                    (tcx.def_span(discr_def_id), format!("`{dis}`"))
1755                }
1756            }
1757            // This should not happen.
1758            ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1759            ty::VariantDiscr::Relative(distance_to_explicit) => {
1760                // At this point we know this discriminant is a duplicate, and was not explicitly
1761                // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1762                // explicitly assigned discriminant, and letting the user know that this was the
1763                // increment startpoint, and how many steps from there leading to the duplicate
1764                if let Some(explicit_idx) =
1765                    idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1766                {
1767                    let explicit_variant = adt.variant(explicit_idx);
1768                    let ve_ident = var.name;
1769                    let ex_ident = explicit_variant.name;
1770                    let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1771
1772                    err.span_label(
1773                        tcx.def_span(explicit_variant.def_id),
1774                        format!(
1775                            "discriminant for `{ve_ident}` incremented from this startpoint \
1776                            (`{ex_ident}` + {distance_to_explicit} {sp} later \
1777                             => `{ve_ident}` = {dis})"
1778                        ),
1779                    );
1780                }
1781
1782                (tcx.def_span(var.def_id), format!("`{dis}`"))
1783            }
1784        };
1785
1786        err.span_label(span, format!("{display_discr} assigned here"));
1787    };
1788
1789    let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1790
1791    // Here we loop through the discriminants, comparing each discriminant to another.
1792    // When a duplicate is detected, we instantiate an error and point to both
1793    // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1794    // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1795    // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1796    // style as we are mutating `discrs` on the fly).
1797    let mut i = 0;
1798    while i < discrs.len() {
1799        let var_i_idx = discrs[i].0;
1800        let mut error: Option<Diag<'_, _>> = None;
1801
1802        let mut o = i + 1;
1803        while o < discrs.len() {
1804            let var_o_idx = discrs[o].0;
1805
1806            if discrs[i].1.val == discrs[o].1.val {
1807                let err = error.get_or_insert_with(|| {
1808                    let mut ret = struct_span_code_err!(
1809                        tcx.dcx(),
1810                        tcx.def_span(adt.did()),
1811                        E0081,
1812                        "discriminant value `{}` assigned more than once",
1813                        discrs[i].1,
1814                    );
1815
1816                    report(discrs[i].1, var_i_idx, &mut ret);
1817
1818                    ret
1819                });
1820
1821                report(discrs[o].1, var_o_idx, err);
1822
1823                // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1824                discrs[o] = *discrs.last().unwrap();
1825                discrs.pop();
1826            } else {
1827                o += 1;
1828            }
1829        }
1830
1831        if let Some(e) = error {
1832            e.emit();
1833        }
1834
1835        i += 1;
1836    }
1837}
1838
1839fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1840    if tcx.type_alias_is_lazy(def_id) {
1841        // Since we compute the variances for lazy type aliases and already reject bivariant
1842        // parameters as unused, we can and should skip this check for lazy type aliases.
1843        return;
1844    }
1845
1846    let generics = tcx.generics_of(def_id);
1847    if generics.own_counts().types == 0 {
1848        return;
1849    }
1850
1851    let ty = tcx.type_of(def_id).instantiate_identity();
1852    if ty.references_error() {
1853        // If there is already another error, do not emit an error for not using a type parameter.
1854        return;
1855    }
1856
1857    // Lazily calculated because it is only needed in case of an error.
1858    let bounded_params = LazyCell::new(|| {
1859        tcx.explicit_predicates_of(def_id)
1860            .predicates
1861            .iter()
1862            .filter_map(|(predicate, span)| {
1863                let bounded_ty = match predicate.kind().skip_binder() {
1864                    ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1865                    ty::ClauseKind::TypeOutlives(pred) => pred.0,
1866                    _ => return None,
1867                };
1868                if let ty::Param(param) = bounded_ty.kind() {
1869                    Some((param.index, span))
1870                } else {
1871                    None
1872                }
1873            })
1874            // FIXME: This assumes that elaborated `Sized` bounds come first (which does hold at the
1875            // time of writing). This is a bit fragile since we later use the span to detect elaborated
1876            // `Sized` bounds. If they came last for example, this would break `Trait + /*elab*/Sized`
1877            // since it would overwrite the span of the user-written bound. This could be fixed by
1878            // folding the spans with `Span::to` which requires a bit of effort I think.
1879            .collect::<FxIndexMap<_, _>>()
1880    });
1881
1882    let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1883    for leaf in ty.walk() {
1884        if let GenericArgKind::Type(leaf_ty) = leaf.kind()
1885            && let ty::Param(param) = leaf_ty.kind()
1886        {
1887            debug!("found use of ty param {:?}", param);
1888            params_used.insert(param.index);
1889        }
1890    }
1891
1892    for param in &generics.own_params {
1893        if !params_used.contains(param.index)
1894            && let ty::GenericParamDefKind::Type { .. } = param.kind
1895        {
1896            let span = tcx.def_span(param.def_id);
1897            let param_name = Ident::new(param.name, span);
1898
1899            // The corresponding predicates are post-`Sized`-elaboration. Therefore we
1900            // * check for emptiness to detect lone user-written `?Sized` bounds
1901            // * compare the param span to the pred span to detect lone user-written `Sized` bounds
1902            let has_explicit_bounds = bounded_params.is_empty()
1903                || (*bounded_params).get(&param.index).is_some_and(|&&pred_sp| pred_sp != span);
1904            let const_param_help = !has_explicit_bounds;
1905
1906            let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
1907                span,
1908                param_name,
1909                param_def_kind: tcx.def_descr(param.def_id),
1910                help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
1911                usage_spans: vec![],
1912                const_param_help,
1913            });
1914            diag.code(E0091);
1915            diag.emit();
1916        }
1917    }
1918}
1919
1920/// Emit an error for recursive opaque types.
1921///
1922/// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1923/// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1924/// `impl Trait`.
1925///
1926/// If all the return expressions evaluate to `!`, then we explain that the error will go away
1927/// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1928fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
1929    let span = tcx.def_span(opaque_def_id);
1930    let mut err = struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
1931
1932    let mut label = false;
1933    if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
1934        let typeck_results = tcx.typeck(def_id);
1935        if visitor
1936            .returns
1937            .iter()
1938            .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1939            .all(|ty| matches!(ty.kind(), ty::Never))
1940        {
1941            let spans = visitor
1942                .returns
1943                .iter()
1944                .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1945                .map(|expr| expr.span)
1946                .collect::<Vec<Span>>();
1947            let span_len = spans.len();
1948            if span_len == 1 {
1949                err.span_label(spans[0], "this returned value is of `!` type");
1950            } else {
1951                let mut multispan: MultiSpan = spans.clone().into();
1952                for span in spans {
1953                    multispan.push_span_label(span, "this returned value is of `!` type");
1954                }
1955                err.span_note(multispan, "these returned values have a concrete \"never\" type");
1956            }
1957            err.help("this error will resolve once the item's body returns a concrete type");
1958        } else {
1959            let mut seen = FxHashSet::default();
1960            seen.insert(span);
1961            err.span_label(span, "recursive opaque type");
1962            label = true;
1963            for (sp, ty) in visitor
1964                .returns
1965                .iter()
1966                .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1967                .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1968            {
1969                #[derive(Default)]
1970                struct OpaqueTypeCollector {
1971                    opaques: Vec<DefId>,
1972                    closures: Vec<DefId>,
1973                }
1974                impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
1975                    fn visit_ty(&mut self, t: Ty<'tcx>) {
1976                        match *t.kind() {
1977                            ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1978                                self.opaques.push(def);
1979                            }
1980                            ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
1981                                self.closures.push(def_id);
1982                                t.super_visit_with(self);
1983                            }
1984                            _ => t.super_visit_with(self),
1985                        }
1986                    }
1987                }
1988
1989                let mut visitor = OpaqueTypeCollector::default();
1990                ty.visit_with(&mut visitor);
1991                for def_id in visitor.opaques {
1992                    let ty_span = tcx.def_span(def_id);
1993                    if !seen.contains(&ty_span) {
1994                        let descr = if ty.is_impl_trait() { "opaque " } else { "" };
1995                        err.span_label(ty_span, format!("returning this {descr}type `{ty}`"));
1996                        seen.insert(ty_span);
1997                    }
1998                    err.span_label(sp, format!("returning here with type `{ty}`"));
1999                }
2000
2001                for closure_def_id in visitor.closures {
2002                    let Some(closure_local_did) = closure_def_id.as_local() else {
2003                        continue;
2004                    };
2005                    let typeck_results = tcx.typeck(closure_local_did);
2006
2007                    let mut label_match = |ty: Ty<'_>, span| {
2008                        for arg in ty.walk() {
2009                            if let ty::GenericArgKind::Type(ty) = arg.kind()
2010                                && let ty::Alias(
2011                                    ty::Opaque,
2012                                    ty::AliasTy { def_id: captured_def_id, .. },
2013                                ) = *ty.kind()
2014                                && captured_def_id == opaque_def_id.to_def_id()
2015                            {
2016                                err.span_label(
2017                                    span,
2018                                    format!(
2019                                        "{} captures itself here",
2020                                        tcx.def_descr(closure_def_id)
2021                                    ),
2022                                );
2023                            }
2024                        }
2025                    };
2026
2027                    // Label any closure upvars that capture the opaque
2028                    for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
2029                    {
2030                        label_match(capture.place.ty(), capture.get_path_span(tcx));
2031                    }
2032                    // Label any coroutine locals that capture the opaque
2033                    if tcx.is_coroutine(closure_def_id)
2034                        && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
2035                    {
2036                        for interior_ty in &coroutine_layout.field_tys {
2037                            label_match(interior_ty.ty, interior_ty.source_info.span);
2038                        }
2039                    }
2040                }
2041            }
2042        }
2043    }
2044    if !label {
2045        err.span_label(span, "cannot resolve opaque type");
2046    }
2047    err.emit()
2048}
2049
2050pub(super) fn check_coroutine_obligations(
2051    tcx: TyCtxt<'_>,
2052    def_id: LocalDefId,
2053) -> Result<(), ErrorGuaranteed> {
2054    debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
2055
2056    let typeck_results = tcx.typeck(def_id);
2057    let param_env = tcx.param_env(def_id);
2058
2059    debug!(?typeck_results.coroutine_stalled_predicates);
2060
2061    let mode = if tcx.next_trait_solver_globally() {
2062        // This query is conceptually between HIR typeck and
2063        // MIR borrowck. We use the opaque types defined by HIR
2064        // and ignore region constraints.
2065        TypingMode::borrowck(tcx, def_id)
2066    } else {
2067        TypingMode::analysis_in_body(tcx, def_id)
2068    };
2069
2070    // Typeck writeback gives us predicates with their regions erased.
2071    // We only need to check the goals while ignoring lifetimes to give good
2072    // error message and to avoid breaking the assumption of `mir_borrowck`
2073    // that all obligations already hold modulo regions.
2074    let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2075
2076    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2077    for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2078        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2079    }
2080
2081    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2082    debug!(?errors);
2083    if !errors.is_empty() {
2084        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2085    }
2086
2087    if !tcx.next_trait_solver_globally() {
2088        // Check that any hidden types found when checking these stalled coroutine obligations
2089        // are valid.
2090        for (key, ty) in infcx.take_opaque_types() {
2091            let hidden_type = infcx.resolve_vars_if_possible(ty);
2092            let key = infcx.resolve_vars_if_possible(key);
2093            sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2094        }
2095    } else {
2096        // We're not checking region constraints here, so we can simply drop the
2097        // added opaque type uses in `TypingMode::Borrowck`.
2098        let _ = infcx.take_opaque_types();
2099    }
2100
2101    Ok(())
2102}
2103
2104pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2105    tcx: TyCtxt<'tcx>,
2106    def_id: LocalDefId,
2107) -> Result<(), ErrorGuaranteed> {
2108    if !tcx.next_trait_solver_globally() {
2109        return Ok(());
2110    }
2111    let typeck_results = tcx.typeck(def_id);
2112    let param_env = tcx.param_env(def_id);
2113
2114    // We use `TypingMode::Borrowck` as we want to use the opaque types computed by HIR typeck.
2115    let typing_mode = TypingMode::borrowck(tcx, def_id);
2116    let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2117    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2118    for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2119        let predicate = fold_regions(tcx, *predicate, |_, _| {
2120            infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2121        });
2122        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2123    }
2124
2125    let errors = ocx.evaluate_obligations_error_on_ambiguity();
2126    debug!(?errors);
2127    if errors.is_empty() { Ok(()) } else { Err(infcx.err_ctxt().report_fulfillment_errors(errors)) }
2128}