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                        check_c_variadic_abi(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::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1013                ty::AssocContainer::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::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {}
1030                ty::AssocContainer::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::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1047                ty::AssocContainer::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 = match ty_impl_item.expect_trait_impl() {
1181            Ok(trait_item_id) => tcx.associated_item(trait_item_id),
1182            Err(ErrorGuaranteed { .. }) => continue,
1183        };
1184
1185        let res = tcx.ensure_ok().compare_impl_item(impl_item.expect_local());
1186
1187        if res.is_ok() {
1188            match ty_impl_item.kind {
1189                ty::AssocKind::Fn { .. } => {
1190                    compare_impl_item::refine::check_refining_return_position_impl_trait_in_trait(
1191                        tcx,
1192                        ty_impl_item,
1193                        ty_trait_item,
1194                        tcx.impl_trait_ref(ty_impl_item.container_id(tcx))
1195                            .unwrap()
1196                            .instantiate_identity(),
1197                    );
1198                }
1199                ty::AssocKind::Const { .. } => {}
1200                ty::AssocKind::Type { .. } => {}
1201            }
1202        }
1203
1204        if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1205            tcx.emit_node_span_lint(
1206                rustc_lint_defs::builtin::DEAD_CODE,
1207                tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
1208                tcx.def_span(ty_impl_item.def_id),
1209                errors::UselessImplItem,
1210            )
1211        }
1212
1213        check_specialization_validity(
1214            tcx,
1215            trait_def,
1216            ty_trait_item,
1217            impl_id.to_def_id(),
1218            impl_item,
1219        );
1220    }
1221
1222    if let Ok(ancestors) = trait_def.ancestors(tcx, impl_id.to_def_id()) {
1223        // Check for missing items from trait
1224        let mut missing_items = Vec::new();
1225
1226        let mut must_implement_one_of: Option<&[Ident]> =
1227            trait_def.must_implement_one_of.as_deref();
1228
1229        for &trait_item_id in tcx.associated_item_def_ids(trait_ref.def_id) {
1230            let leaf_def = ancestors.leaf_def(tcx, trait_item_id);
1231
1232            let is_implemented = leaf_def
1233                .as_ref()
1234                .is_some_and(|node_item| node_item.item.defaultness(tcx).has_value());
1235
1236            if !is_implemented
1237                && tcx.defaultness(impl_id).is_final()
1238                // unsized types don't need to implement methods that have `Self: Sized` bounds.
1239                && !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
1240            {
1241                missing_items.push(tcx.associated_item(trait_item_id));
1242            }
1243
1244            // true if this item is specifically implemented in this impl
1245            let is_implemented_here =
1246                leaf_def.as_ref().is_some_and(|node_item| !node_item.defining_node.is_from_trait());
1247
1248            if !is_implemented_here {
1249                let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1250                match tcx.eval_default_body_stability(trait_item_id, full_impl_span) {
1251                    EvalResult::Deny { feature, reason, issue, .. } => default_body_is_unstable(
1252                        tcx,
1253                        full_impl_span,
1254                        trait_item_id,
1255                        feature,
1256                        reason,
1257                        issue,
1258                    ),
1259
1260                    // Unmarked default bodies are considered stable (at least for now).
1261                    EvalResult::Allow | EvalResult::Unmarked => {}
1262                }
1263            }
1264
1265            if let Some(required_items) = &must_implement_one_of {
1266                if is_implemented_here {
1267                    let trait_item = tcx.associated_item(trait_item_id);
1268                    if required_items.contains(&trait_item.ident(tcx)) {
1269                        must_implement_one_of = None;
1270                    }
1271                }
1272            }
1273
1274            if let Some(leaf_def) = &leaf_def
1275                && !leaf_def.is_final()
1276                && let def_id = leaf_def.item.def_id
1277                && tcx.impl_method_has_trait_impl_trait_tys(def_id)
1278            {
1279                let def_kind = tcx.def_kind(def_id);
1280                let descr = tcx.def_kind_descr(def_kind, def_id);
1281                let (msg, feature) = if tcx.asyncness(def_id).is_async() {
1282                    (
1283                        format!("async {descr} in trait cannot be specialized"),
1284                        "async functions in traits",
1285                    )
1286                } else {
1287                    (
1288                        format!(
1289                            "{descr} with return-position `impl Trait` in trait cannot be specialized"
1290                        ),
1291                        "return position `impl Trait` in traits",
1292                    )
1293                };
1294                tcx.dcx()
1295                    .struct_span_err(tcx.def_span(def_id), msg)
1296                    .with_note(format!(
1297                        "specialization behaves in inconsistent and surprising ways with \
1298                        {feature}, and for now is disallowed"
1299                    ))
1300                    .emit();
1301            }
1302        }
1303
1304        if !missing_items.is_empty() {
1305            let full_impl_span = tcx.hir_span_with_body(tcx.local_def_id_to_hir_id(impl_id));
1306            missing_items_err(tcx, impl_id, &missing_items, full_impl_span);
1307        }
1308
1309        if let Some(missing_items) = must_implement_one_of {
1310            let attr_span = tcx
1311                .get_attr(trait_ref.def_id, sym::rustc_must_implement_one_of)
1312                .map(|attr| attr.span());
1313
1314            missing_items_must_implement_one_of_err(
1315                tcx,
1316                tcx.def_span(impl_id),
1317                missing_items,
1318                attr_span,
1319            );
1320        }
1321    }
1322}
1323
1324fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) {
1325    let t = tcx.type_of(def_id).instantiate_identity();
1326    if let ty::Adt(def, args) = t.kind()
1327        && def.is_struct()
1328    {
1329        let fields = &def.non_enum_variant().fields;
1330        if fields.is_empty() {
1331            struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1332            return;
1333        }
1334
1335        let array_field = &fields[FieldIdx::ZERO];
1336        let array_ty = array_field.ty(tcx, args);
1337        let ty::Array(element_ty, len_const) = array_ty.kind() else {
1338            struct_span_code_err!(
1339                tcx.dcx(),
1340                sp,
1341                E0076,
1342                "SIMD vector's only field must be an array"
1343            )
1344            .with_span_label(tcx.def_span(array_field.did), "not an array")
1345            .emit();
1346            return;
1347        };
1348
1349        if let Some(second_field) = fields.get(FieldIdx::ONE) {
1350            struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot have multiple fields")
1351                .with_span_label(tcx.def_span(second_field.did), "excess field")
1352                .emit();
1353            return;
1354        }
1355
1356        // FIXME(repr_simd): This check is nice, but perhaps unnecessary due to the fact
1357        // we do not expect users to implement their own `repr(simd)` types. If they could,
1358        // this check is easily side-steppable by hiding the const behind normalization.
1359        // The consequence is that the error is, in general, only observable post-mono.
1360        if let Some(len) = len_const.try_to_target_usize(tcx) {
1361            if len == 0 {
1362                struct_span_code_err!(tcx.dcx(), sp, E0075, "SIMD vector cannot be empty").emit();
1363                return;
1364            } else if len > MAX_SIMD_LANES {
1365                struct_span_code_err!(
1366                    tcx.dcx(),
1367                    sp,
1368                    E0075,
1369                    "SIMD vector cannot have more than {MAX_SIMD_LANES} elements",
1370                )
1371                .emit();
1372                return;
1373            }
1374        }
1375
1376        // Check that we use types valid for use in the lanes of a SIMD "vector register"
1377        // These are scalar types which directly match a "machine" type
1378        // Yes: Integers, floats, "thin" pointers
1379        // No: char, "wide" pointers, compound types
1380        match element_ty.kind() {
1381            ty::Param(_) => (), // pass struct<T>([T; 4]) through, let monomorphization catch errors
1382            ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::RawPtr(_, _) => (), // struct([u8; 4]) is ok
1383            _ => {
1384                struct_span_code_err!(
1385                    tcx.dcx(),
1386                    sp,
1387                    E0077,
1388                    "SIMD vector element type should be a \
1389                        primitive scalar (integer/float/pointer) type"
1390                )
1391                .emit();
1392                return;
1393            }
1394        }
1395    }
1396}
1397
1398pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
1399    let repr = def.repr();
1400    if repr.packed() {
1401        if let Some(reprs) = find_attr!(tcx.get_all_attrs(def.did()), attrs::AttributeKind::Repr { reprs, .. } => reprs)
1402        {
1403            for (r, _) in reprs {
1404                if let ReprPacked(pack) = r
1405                    && let Some(repr_pack) = repr.pack
1406                    && pack != &repr_pack
1407                {
1408                    struct_span_code_err!(
1409                        tcx.dcx(),
1410                        sp,
1411                        E0634,
1412                        "type has conflicting packed representation hints"
1413                    )
1414                    .emit();
1415                }
1416            }
1417        }
1418        if repr.align.is_some() {
1419            struct_span_code_err!(
1420                tcx.dcx(),
1421                sp,
1422                E0587,
1423                "type has conflicting packed and align representation hints"
1424            )
1425            .emit();
1426        } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
1427            let mut err = struct_span_code_err!(
1428                tcx.dcx(),
1429                sp,
1430                E0588,
1431                "packed type cannot transitively contain a `#[repr(align)]` type"
1432            );
1433
1434            err.span_note(
1435                tcx.def_span(def_spans[0].0),
1436                format!("`{}` has a `#[repr(align)]` attribute", tcx.item_name(def_spans[0].0)),
1437            );
1438
1439            if def_spans.len() > 2 {
1440                let mut first = true;
1441                for (adt_def, span) in def_spans.iter().skip(1).rev() {
1442                    let ident = tcx.item_name(*adt_def);
1443                    err.span_note(
1444                        *span,
1445                        if first {
1446                            format!(
1447                                "`{}` contains a field of type `{}`",
1448                                tcx.type_of(def.did()).instantiate_identity(),
1449                                ident
1450                            )
1451                        } else {
1452                            format!("...which contains a field of type `{ident}`")
1453                        },
1454                    );
1455                    first = false;
1456                }
1457            }
1458
1459            err.emit();
1460        }
1461    }
1462}
1463
1464pub(super) fn check_packed_inner(
1465    tcx: TyCtxt<'_>,
1466    def_id: DefId,
1467    stack: &mut Vec<DefId>,
1468) -> Option<Vec<(DefId, Span)>> {
1469    if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() {
1470        if def.is_struct() || def.is_union() {
1471            if def.repr().align.is_some() {
1472                return Some(vec![(def.did(), DUMMY_SP)]);
1473            }
1474
1475            stack.push(def_id);
1476            for field in &def.non_enum_variant().fields {
1477                if let ty::Adt(def, _) = field.ty(tcx, args).kind()
1478                    && !stack.contains(&def.did())
1479                    && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack)
1480                {
1481                    defs.push((def.did(), field.ident(tcx).span));
1482                    return Some(defs);
1483                }
1484            }
1485            stack.pop();
1486        }
1487    }
1488
1489    None
1490}
1491
1492pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1493    if !adt.repr().transparent() {
1494        return;
1495    }
1496
1497    if adt.is_union() && !tcx.features().transparent_unions() {
1498        feature_err(
1499            &tcx.sess,
1500            sym::transparent_unions,
1501            tcx.def_span(adt.did()),
1502            "transparent unions are unstable",
1503        )
1504        .emit();
1505    }
1506
1507    if adt.variants().len() != 1 {
1508        bad_variant_count(tcx, adt, tcx.def_span(adt.did()), adt.did());
1509        // Don't bother checking the fields.
1510        return;
1511    }
1512
1513    // For each field, figure out if it's known to have "trivial" layout (i.e., is a 1-ZST), with
1514    // "known" respecting #[non_exhaustive] attributes.
1515    let field_infos = adt.all_fields().map(|field| {
1516        let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did));
1517        let typing_env = ty::TypingEnv::non_body_analysis(tcx, field.did);
1518        let layout = tcx.layout_of(typing_env.as_query_input(ty));
1519        // We are currently checking the type this field came from, so it must be local
1520        let span = tcx.hir_span_if_local(field.did).unwrap();
1521        let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1522        if !trivial {
1523            return (span, trivial, None);
1524        }
1525        // Even some 1-ZST fields are not allowed though, if they have `non_exhaustive`.
1526
1527        fn check_non_exhaustive<'tcx>(
1528            tcx: TyCtxt<'tcx>,
1529            t: Ty<'tcx>,
1530        ) -> ControlFlow<(&'static str, DefId, GenericArgsRef<'tcx>, bool)> {
1531            match t.kind() {
1532                ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)),
1533                ty::Array(ty, _) => check_non_exhaustive(tcx, *ty),
1534                ty::Adt(def, args) => {
1535                    if !def.did().is_local()
1536                        && !find_attr!(
1537                            tcx.get_all_attrs(def.did()),
1538                            AttributeKind::PubTransparent(_)
1539                        )
1540                    {
1541                        let non_exhaustive = def.is_variant_list_non_exhaustive()
1542                            || def
1543                                .variants()
1544                                .iter()
1545                                .any(ty::VariantDef::is_field_list_non_exhaustive);
1546                        let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1547                        if non_exhaustive || has_priv {
1548                            return ControlFlow::Break((
1549                                def.descr(),
1550                                def.did(),
1551                                args,
1552                                non_exhaustive,
1553                            ));
1554                        }
1555                    }
1556                    def.all_fields()
1557                        .map(|field| field.ty(tcx, args))
1558                        .try_for_each(|t| check_non_exhaustive(tcx, t))
1559                }
1560                _ => ControlFlow::Continue(()),
1561            }
1562        }
1563
1564        (span, trivial, check_non_exhaustive(tcx, ty).break_value())
1565    });
1566
1567    let non_trivial_fields = field_infos
1568        .clone()
1569        .filter_map(|(span, trivial, _non_exhaustive)| if !trivial { Some(span) } else { None });
1570    let non_trivial_count = non_trivial_fields.clone().count();
1571    if non_trivial_count >= 2 {
1572        bad_non_zero_sized_fields(
1573            tcx,
1574            adt,
1575            non_trivial_count,
1576            non_trivial_fields,
1577            tcx.def_span(adt.did()),
1578        );
1579        return;
1580    }
1581    let mut prev_non_exhaustive_1zst = false;
1582    for (span, _trivial, non_exhaustive_1zst) in field_infos {
1583        if let Some((descr, def_id, args, non_exhaustive)) = non_exhaustive_1zst {
1584            // If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
1585            // Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
1586            if non_trivial_count > 0 || prev_non_exhaustive_1zst {
1587                tcx.node_span_lint(
1588                    REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS,
1589                    tcx.local_def_id_to_hir_id(adt.did().expect_local()),
1590                    span,
1591                    |lint| {
1592                        lint.primary_message(
1593                            "zero-sized fields in `repr(transparent)` cannot \
1594                             contain external non-exhaustive types",
1595                        );
1596                        let note = if non_exhaustive {
1597                            "is marked with `#[non_exhaustive]`"
1598                        } else {
1599                            "contains private fields"
1600                        };
1601                        let field_ty = tcx.def_path_str_with_args(def_id, args);
1602                        lint.note(format!(
1603                            "this {descr} contains `{field_ty}`, which {note}, \
1604                                and makes it not a breaking change to become \
1605                                non-zero-sized in the future."
1606                        ));
1607                    },
1608                )
1609            } else {
1610                prev_non_exhaustive_1zst = true;
1611            }
1612        }
1613    }
1614}
1615
1616#[allow(trivial_numeric_casts)]
1617fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
1618    let def = tcx.adt_def(def_id);
1619    def.destructor(tcx); // force the destructor to be evaluated
1620
1621    if def.variants().is_empty() {
1622        find_attr!(
1623            tcx.get_all_attrs(def_id),
1624            attrs::AttributeKind::Repr { reprs, first_span } => {
1625                struct_span_code_err!(
1626                    tcx.dcx(),
1627                    reprs.first().map(|repr| repr.1).unwrap_or(*first_span),
1628                    E0084,
1629                    "unsupported representation for zero-variant enum"
1630                )
1631                .with_span_label(tcx.def_span(def_id), "zero-variant enum")
1632                .emit();
1633            }
1634        );
1635    }
1636
1637    for v in def.variants() {
1638        if let ty::VariantDiscr::Explicit(discr_def_id) = v.discr {
1639            tcx.ensure_ok().typeck(discr_def_id.expect_local());
1640        }
1641    }
1642
1643    if def.repr().int.is_none() {
1644        let is_unit = |var: &ty::VariantDef| matches!(var.ctor_kind(), Some(CtorKind::Const));
1645        let get_disr = |var: &ty::VariantDef| match var.discr {
1646            ty::VariantDiscr::Explicit(disr) => Some(disr),
1647            ty::VariantDiscr::Relative(_) => None,
1648        };
1649
1650        let non_unit = def.variants().iter().find(|var| !is_unit(var));
1651        let disr_unit =
1652            def.variants().iter().filter(|var| is_unit(var)).find_map(|var| get_disr(var));
1653        let disr_non_unit =
1654            def.variants().iter().filter(|var| !is_unit(var)).find_map(|var| get_disr(var));
1655
1656        if disr_non_unit.is_some() || (disr_unit.is_some() && non_unit.is_some()) {
1657            let mut err = struct_span_code_err!(
1658                tcx.dcx(),
1659                tcx.def_span(def_id),
1660                E0732,
1661                "`#[repr(inttype)]` must be specified for enums with explicit discriminants and non-unit variants"
1662            );
1663            if let Some(disr_non_unit) = disr_non_unit {
1664                err.span_label(
1665                    tcx.def_span(disr_non_unit),
1666                    "explicit discriminant on non-unit variant specified here",
1667                );
1668            } else {
1669                err.span_label(
1670                    tcx.def_span(disr_unit.unwrap()),
1671                    "explicit discriminant specified here",
1672                );
1673                err.span_label(
1674                    tcx.def_span(non_unit.unwrap().def_id),
1675                    "non-unit discriminant declared here",
1676                );
1677            }
1678            err.emit();
1679        }
1680    }
1681
1682    detect_discriminant_duplicate(tcx, def);
1683    check_transparent(tcx, def);
1684}
1685
1686/// Part of enum check. Given the discriminants of an enum, errors if two or more discriminants are equal
1687fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
1688    // Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
1689    // Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
1690    let report = |dis: Discr<'tcx>, idx, err: &mut Diag<'_>| {
1691        let var = adt.variant(idx); // HIR for the duplicate discriminant
1692        let (span, display_discr) = match var.discr {
1693            ty::VariantDiscr::Explicit(discr_def_id) => {
1694                // In the case the discriminant is both a duplicate and overflowed, let the user know
1695                if let hir::Node::AnonConst(expr) =
1696                    tcx.hir_node_by_def_id(discr_def_id.expect_local())
1697                    && let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
1698                    && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
1699                    && *lit_value != dis.val
1700                {
1701                    (tcx.def_span(discr_def_id), format!("`{dis}` (overflowed from `{lit_value}`)"))
1702                } else {
1703                    // Otherwise, format the value as-is
1704                    (tcx.def_span(discr_def_id), format!("`{dis}`"))
1705                }
1706            }
1707            // This should not happen.
1708            ty::VariantDiscr::Relative(0) => (tcx.def_span(var.def_id), format!("`{dis}`")),
1709            ty::VariantDiscr::Relative(distance_to_explicit) => {
1710                // At this point we know this discriminant is a duplicate, and was not explicitly
1711                // assigned by the user. Here we iterate backwards to fetch the HIR for the last
1712                // explicitly assigned discriminant, and letting the user know that this was the
1713                // increment startpoint, and how many steps from there leading to the duplicate
1714                if let Some(explicit_idx) =
1715                    idx.as_u32().checked_sub(distance_to_explicit).map(VariantIdx::from_u32)
1716                {
1717                    let explicit_variant = adt.variant(explicit_idx);
1718                    let ve_ident = var.name;
1719                    let ex_ident = explicit_variant.name;
1720                    let sp = if distance_to_explicit > 1 { "variants" } else { "variant" };
1721
1722                    err.span_label(
1723                        tcx.def_span(explicit_variant.def_id),
1724                        format!(
1725                            "discriminant for `{ve_ident}` incremented from this startpoint \
1726                            (`{ex_ident}` + {distance_to_explicit} {sp} later \
1727                             => `{ve_ident}` = {dis})"
1728                        ),
1729                    );
1730                }
1731
1732                (tcx.def_span(var.def_id), format!("`{dis}`"))
1733            }
1734        };
1735
1736        err.span_label(span, format!("{display_discr} assigned here"));
1737    };
1738
1739    let mut discrs = adt.discriminants(tcx).collect::<Vec<_>>();
1740
1741    // Here we loop through the discriminants, comparing each discriminant to another.
1742    // When a duplicate is detected, we instantiate an error and point to both
1743    // initial and duplicate value. The duplicate discriminant is then discarded by swapping
1744    // it with the last element and decrementing the `vec.len` (which is why we have to evaluate
1745    // `discrs.len()` anew every iteration, and why this could be tricky to do in a functional
1746    // style as we are mutating `discrs` on the fly).
1747    let mut i = 0;
1748    while i < discrs.len() {
1749        let var_i_idx = discrs[i].0;
1750        let mut error: Option<Diag<'_, _>> = None;
1751
1752        let mut o = i + 1;
1753        while o < discrs.len() {
1754            let var_o_idx = discrs[o].0;
1755
1756            if discrs[i].1.val == discrs[o].1.val {
1757                let err = error.get_or_insert_with(|| {
1758                    let mut ret = struct_span_code_err!(
1759                        tcx.dcx(),
1760                        tcx.def_span(adt.did()),
1761                        E0081,
1762                        "discriminant value `{}` assigned more than once",
1763                        discrs[i].1,
1764                    );
1765
1766                    report(discrs[i].1, var_i_idx, &mut ret);
1767
1768                    ret
1769                });
1770
1771                report(discrs[o].1, var_o_idx, err);
1772
1773                // Safe to unwrap here, as we wouldn't reach this point if `discrs` was empty
1774                discrs[o] = *discrs.last().unwrap();
1775                discrs.pop();
1776            } else {
1777                o += 1;
1778            }
1779        }
1780
1781        if let Some(e) = error {
1782            e.emit();
1783        }
1784
1785        i += 1;
1786    }
1787}
1788
1789fn check_type_alias_type_params_are_used<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1790    if tcx.type_alias_is_lazy(def_id) {
1791        // Since we compute the variances for lazy type aliases and already reject bivariant
1792        // parameters as unused, we can and should skip this check for lazy type aliases.
1793        return;
1794    }
1795
1796    let generics = tcx.generics_of(def_id);
1797    if generics.own_counts().types == 0 {
1798        return;
1799    }
1800
1801    let ty = tcx.type_of(def_id).instantiate_identity();
1802    if ty.references_error() {
1803        // If there is already another error, do not emit an error for not using a type parameter.
1804        return;
1805    }
1806
1807    // Lazily calculated because it is only needed in case of an error.
1808    let bounded_params = LazyCell::new(|| {
1809        tcx.explicit_predicates_of(def_id)
1810            .predicates
1811            .iter()
1812            .filter_map(|(predicate, span)| {
1813                let bounded_ty = match predicate.kind().skip_binder() {
1814                    ty::ClauseKind::Trait(pred) => pred.trait_ref.self_ty(),
1815                    ty::ClauseKind::TypeOutlives(pred) => pred.0,
1816                    _ => return None,
1817                };
1818                if let ty::Param(param) = bounded_ty.kind() {
1819                    Some((param.index, span))
1820                } else {
1821                    None
1822                }
1823            })
1824            // FIXME: This assumes that elaborated `Sized` bounds come first (which does hold at the
1825            // time of writing). This is a bit fragile since we later use the span to detect elaborated
1826            // `Sized` bounds. If they came last for example, this would break `Trait + /*elab*/Sized`
1827            // since it would overwrite the span of the user-written bound. This could be fixed by
1828            // folding the spans with `Span::to` which requires a bit of effort I think.
1829            .collect::<FxIndexMap<_, _>>()
1830    });
1831
1832    let mut params_used = DenseBitSet::new_empty(generics.own_params.len());
1833    for leaf in ty.walk() {
1834        if let GenericArgKind::Type(leaf_ty) = leaf.kind()
1835            && let ty::Param(param) = leaf_ty.kind()
1836        {
1837            debug!("found use of ty param {:?}", param);
1838            params_used.insert(param.index);
1839        }
1840    }
1841
1842    for param in &generics.own_params {
1843        if !params_used.contains(param.index)
1844            && let ty::GenericParamDefKind::Type { .. } = param.kind
1845        {
1846            let span = tcx.def_span(param.def_id);
1847            let param_name = Ident::new(param.name, span);
1848
1849            // The corresponding predicates are post-`Sized`-elaboration. Therefore we
1850            // * check for emptiness to detect lone user-written `?Sized` bounds
1851            // * compare the param span to the pred span to detect lone user-written `Sized` bounds
1852            let has_explicit_bounds = bounded_params.is_empty()
1853                || (*bounded_params).get(&param.index).is_some_and(|&&pred_sp| pred_sp != span);
1854            let const_param_help = !has_explicit_bounds;
1855
1856            let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
1857                span,
1858                param_name,
1859                param_def_kind: tcx.def_descr(param.def_id),
1860                help: errors::UnusedGenericParameterHelp::TyAlias { param_name },
1861                usage_spans: vec![],
1862                const_param_help,
1863            });
1864            diag.code(E0091);
1865            diag.emit();
1866        }
1867    }
1868}
1869
1870/// Emit an error for recursive opaque types.
1871///
1872/// If this is a return `impl Trait`, find the item's return expressions and point at them. For
1873/// direct recursion this is enough, but for indirect recursion also point at the last intermediary
1874/// `impl Trait`.
1875///
1876/// If all the return expressions evaluate to `!`, then we explain that the error will go away
1877/// after changing it. This can happen when a user uses `panic!()` or similar as a placeholder.
1878fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorGuaranteed {
1879    let span = tcx.def_span(opaque_def_id);
1880    let mut err = struct_span_code_err!(tcx.dcx(), span, E0720, "cannot resolve opaque type");
1881
1882    let mut label = false;
1883    if let Some((def_id, visitor)) = get_owner_return_paths(tcx, opaque_def_id) {
1884        let typeck_results = tcx.typeck(def_id);
1885        if visitor
1886            .returns
1887            .iter()
1888            .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id))
1889            .all(|ty| matches!(ty.kind(), ty::Never))
1890        {
1891            let spans = visitor
1892                .returns
1893                .iter()
1894                .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some())
1895                .map(|expr| expr.span)
1896                .collect::<Vec<Span>>();
1897            let span_len = spans.len();
1898            if span_len == 1 {
1899                err.span_label(spans[0], "this returned value is of `!` type");
1900            } else {
1901                let mut multispan: MultiSpan = spans.clone().into();
1902                for span in spans {
1903                    multispan.push_span_label(span, "this returned value is of `!` type");
1904                }
1905                err.span_note(multispan, "these returned values have a concrete \"never\" type");
1906            }
1907            err.help("this error will resolve once the item's body returns a concrete type");
1908        } else {
1909            let mut seen = FxHashSet::default();
1910            seen.insert(span);
1911            err.span_label(span, "recursive opaque type");
1912            label = true;
1913            for (sp, ty) in visitor
1914                .returns
1915                .iter()
1916                .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t)))
1917                .filter(|(_, ty)| !matches!(ty.kind(), ty::Never))
1918            {
1919                #[derive(Default)]
1920                struct OpaqueTypeCollector {
1921                    opaques: Vec<DefId>,
1922                    closures: Vec<DefId>,
1923                }
1924                impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector {
1925                    fn visit_ty(&mut self, t: Ty<'tcx>) {
1926                        match *t.kind() {
1927                            ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1928                                self.opaques.push(def);
1929                            }
1930                            ty::Closure(def_id, ..) | ty::Coroutine(def_id, ..) => {
1931                                self.closures.push(def_id);
1932                                t.super_visit_with(self);
1933                            }
1934                            _ => t.super_visit_with(self),
1935                        }
1936                    }
1937                }
1938
1939                let mut visitor = OpaqueTypeCollector::default();
1940                ty.visit_with(&mut visitor);
1941                for def_id in visitor.opaques {
1942                    let ty_span = tcx.def_span(def_id);
1943                    if !seen.contains(&ty_span) {
1944                        let descr = if ty.is_impl_trait() { "opaque " } else { "" };
1945                        err.span_label(ty_span, format!("returning this {descr}type `{ty}`"));
1946                        seen.insert(ty_span);
1947                    }
1948                    err.span_label(sp, format!("returning here with type `{ty}`"));
1949                }
1950
1951                for closure_def_id in visitor.closures {
1952                    let Some(closure_local_did) = closure_def_id.as_local() else {
1953                        continue;
1954                    };
1955                    let typeck_results = tcx.typeck(closure_local_did);
1956
1957                    let mut label_match = |ty: Ty<'_>, span| {
1958                        for arg in ty.walk() {
1959                            if let ty::GenericArgKind::Type(ty) = arg.kind()
1960                                && let ty::Alias(
1961                                    ty::Opaque,
1962                                    ty::AliasTy { def_id: captured_def_id, .. },
1963                                ) = *ty.kind()
1964                                && captured_def_id == opaque_def_id.to_def_id()
1965                            {
1966                                err.span_label(
1967                                    span,
1968                                    format!(
1969                                        "{} captures itself here",
1970                                        tcx.def_descr(closure_def_id)
1971                                    ),
1972                                );
1973                            }
1974                        }
1975                    };
1976
1977                    // Label any closure upvars that capture the opaque
1978                    for capture in typeck_results.closure_min_captures_flattened(closure_local_did)
1979                    {
1980                        label_match(capture.place.ty(), capture.get_path_span(tcx));
1981                    }
1982                    // Label any coroutine locals that capture the opaque
1983                    if tcx.is_coroutine(closure_def_id)
1984                        && let Some(coroutine_layout) = tcx.mir_coroutine_witnesses(closure_def_id)
1985                    {
1986                        for interior_ty in &coroutine_layout.field_tys {
1987                            label_match(interior_ty.ty, interior_ty.source_info.span);
1988                        }
1989                    }
1990                }
1991            }
1992        }
1993    }
1994    if !label {
1995        err.span_label(span, "cannot resolve opaque type");
1996    }
1997    err.emit()
1998}
1999
2000pub(super) fn check_coroutine_obligations(
2001    tcx: TyCtxt<'_>,
2002    def_id: LocalDefId,
2003) -> Result<(), ErrorGuaranteed> {
2004    debug_assert!(!tcx.is_typeck_child(def_id.to_def_id()));
2005
2006    let typeck_results = tcx.typeck(def_id);
2007    let param_env = tcx.param_env(def_id);
2008
2009    debug!(?typeck_results.coroutine_stalled_predicates);
2010
2011    let mode = if tcx.next_trait_solver_globally() {
2012        // This query is conceptually between HIR typeck and
2013        // MIR borrowck. We use the opaque types defined by HIR
2014        // and ignore region constraints.
2015        TypingMode::borrowck(tcx, def_id)
2016    } else {
2017        TypingMode::analysis_in_body(tcx, def_id)
2018    };
2019
2020    // Typeck writeback gives us predicates with their regions erased.
2021    // We only need to check the goals while ignoring lifetimes to give good
2022    // error message and to avoid breaking the assumption of `mir_borrowck`
2023    // that all obligations already hold modulo regions.
2024    let infcx = tcx.infer_ctxt().ignoring_regions().build(mode);
2025
2026    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2027    for (predicate, cause) in &typeck_results.coroutine_stalled_predicates {
2028        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, *predicate));
2029    }
2030
2031    let errors = ocx.select_all_or_error();
2032    debug!(?errors);
2033    if !errors.is_empty() {
2034        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
2035    }
2036
2037    if !tcx.next_trait_solver_globally() {
2038        // Check that any hidden types found when checking these stalled coroutine obligations
2039        // are valid.
2040        for (key, ty) in infcx.take_opaque_types() {
2041            let hidden_type = infcx.resolve_vars_if_possible(ty);
2042            let key = infcx.resolve_vars_if_possible(key);
2043            sanity_check_found_hidden_type(tcx, key, hidden_type)?;
2044        }
2045    } else {
2046        // We're not checking region constraints here, so we can simply drop the
2047        // added opaque type uses in `TypingMode::Borrowck`.
2048        let _ = infcx.take_opaque_types();
2049    }
2050
2051    Ok(())
2052}
2053
2054pub(super) fn check_potentially_region_dependent_goals<'tcx>(
2055    tcx: TyCtxt<'tcx>,
2056    def_id: LocalDefId,
2057) -> Result<(), ErrorGuaranteed> {
2058    if !tcx.next_trait_solver_globally() {
2059        return Ok(());
2060    }
2061    let typeck_results = tcx.typeck(def_id);
2062    let param_env = tcx.param_env(def_id);
2063
2064    // We use `TypingMode::Borrowck` as we want to use the opaque types computed by HIR typeck.
2065    let typing_mode = TypingMode::borrowck(tcx, def_id);
2066    let infcx = tcx.infer_ctxt().ignoring_regions().build(typing_mode);
2067    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
2068    for (predicate, cause) in &typeck_results.potentially_region_dependent_goals {
2069        let predicate = fold_regions(tcx, *predicate, |_, _| {
2070            infcx.next_region_var(RegionVariableOrigin::Misc(cause.span))
2071        });
2072        ocx.register_obligation(Obligation::new(tcx, cause.clone(), param_env, predicate));
2073    }
2074
2075    let errors = ocx.select_all_or_error();
2076    debug!(?errors);
2077    if errors.is_empty() { Ok(()) } else { Err(infcx.err_ctxt().report_fulfillment_errors(errors)) }
2078}