rustc_hir_analysis/check/
check.rs

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