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