rustc_hir_analysis/check/
wfcheck.rs

1use std::cell::LazyCell;
2use std::ops::{ControlFlow, Deref};
3
4use hir::intravisit::{self, Visitor};
5use rustc_abi::ExternAbi;
6use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
7use rustc_errors::codes::*;
8use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err};
9use rustc_hir::def::{DefKind, Res};
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::lang_items::LangItem;
12use rustc_hir::{AmbigArg, ItemKind};
13use rustc_infer::infer::outlives::env::OutlivesEnvironment;
14use rustc_infer::infer::{self, InferCtxt, SubregionOrigin, TyCtxtInferExt};
15use rustc_lint_defs::builtin::SUPERTRAIT_ITEM_SHADOWING_DEFINITION;
16use rustc_macros::LintDiagnostic;
17use rustc_middle::mir::interpret::ErrorHandled;
18use rustc_middle::traits::solve::NoSolution;
19use rustc_middle::ty::trait_def::TraitSpecializationKind;
20use rustc_middle::ty::{
21    self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags,
22    TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
23    Upcast,
24};
25use rustc_middle::{bug, span_bug};
26use rustc_session::parse::feature_err;
27use rustc_span::{DUMMY_SP, Span, sym};
28use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
29use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
30use rustc_trait_selection::traits::misc::{
31    ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
32};
33use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
34use rustc_trait_selection::traits::{
35    self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
36    WellFormedLoc,
37};
38use tracing::{debug, instrument};
39use {rustc_ast as ast, rustc_hir as hir};
40
41use crate::autoderef::Autoderef;
42use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params};
43use crate::errors::InvalidReceiverTyHint;
44use crate::{errors, fluent_generated as fluent};
45
46pub(super) struct WfCheckingCtxt<'a, 'tcx> {
47    pub(super) ocx: ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>,
48    body_def_id: LocalDefId,
49    param_env: ty::ParamEnv<'tcx>,
50}
51impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
52    type Target = ObligationCtxt<'a, 'tcx, FulfillmentError<'tcx>>;
53    fn deref(&self) -> &Self::Target {
54        &self.ocx
55    }
56}
57
58impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
59    fn tcx(&self) -> TyCtxt<'tcx> {
60        self.ocx.infcx.tcx
61    }
62
63    // Convenience function to normalize during wfcheck. This performs
64    // `ObligationCtxt::normalize`, but provides a nice `ObligationCauseCode`.
65    fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
66    where
67        T: TypeFoldable<TyCtxt<'tcx>>,
68    {
69        self.ocx.normalize(
70            &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
71            self.param_env,
72            value,
73        )
74    }
75
76    /// Convenience function to *deeply* normalize during wfcheck. In the old solver,
77    /// this just dispatches to [`WfCheckingCtxt::normalize`], but in the new solver
78    /// this calls `deeply_normalize` and reports errors if they are encountered.
79    ///
80    /// This function should be called in favor of `normalize` in cases where we will
81    /// then check the well-formedness of the type, since we only use the normalized
82    /// signature types for implied bounds when checking regions.
83    // FIXME(-Znext-solver): This should be removed when we compute implied outlives
84    // bounds using the unnormalized signature of the function we're checking.
85    pub(super) fn deeply_normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
86    where
87        T: TypeFoldable<TyCtxt<'tcx>>,
88    {
89        if self.infcx.next_trait_solver() {
90            match self.ocx.deeply_normalize(
91                &ObligationCause::new(span, self.body_def_id, ObligationCauseCode::WellFormed(loc)),
92                self.param_env,
93                value.clone(),
94            ) {
95                Ok(value) => value,
96                Err(errors) => {
97                    self.infcx.err_ctxt().report_fulfillment_errors(errors);
98                    value
99                }
100            }
101        } else {
102            self.normalize(span, loc, value)
103        }
104    }
105
106    pub(super) fn register_wf_obligation(
107        &self,
108        span: Span,
109        loc: Option<WellFormedLoc>,
110        term: ty::Term<'tcx>,
111    ) {
112        let cause = traits::ObligationCause::new(
113            span,
114            self.body_def_id,
115            ObligationCauseCode::WellFormed(loc),
116        );
117        self.ocx.register_obligation(Obligation::new(
118            self.tcx(),
119            cause,
120            self.param_env,
121            ty::ClauseKind::WellFormed(term),
122        ));
123    }
124}
125
126pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
127    tcx: TyCtxt<'tcx>,
128    body_def_id: LocalDefId,
129    f: F,
130) -> Result<(), ErrorGuaranteed>
131where
132    F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> Result<(), ErrorGuaranteed>,
133{
134    let param_env = tcx.param_env(body_def_id);
135    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
136    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
137
138    let mut wfcx = WfCheckingCtxt { ocx, body_def_id, param_env };
139
140    if !tcx.features().trivial_bounds() {
141        wfcx.check_false_global_bounds()
142    }
143    f(&mut wfcx)?;
144
145    let errors = wfcx.select_all_or_error();
146    if !errors.is_empty() {
147        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
148    }
149
150    let assumed_wf_types = wfcx.ocx.assumed_wf_types_and_report_errors(param_env, body_def_id)?;
151    debug!(?assumed_wf_types);
152
153    let infcx_compat = infcx.fork();
154
155    // We specifically want to *disable* the implied bounds hack, first,
156    // so we can detect when failures are due to bevy's implied bounds.
157    let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
158        &infcx,
159        body_def_id,
160        param_env,
161        assumed_wf_types.iter().copied(),
162        true,
163    );
164
165    lint_redundant_lifetimes(tcx, body_def_id, &outlives_env);
166
167    let errors = infcx.resolve_regions_with_outlives_env(&outlives_env);
168    if errors.is_empty() {
169        return Ok(());
170    }
171
172    let outlives_env = OutlivesEnvironment::new_with_implied_bounds_compat(
173        &infcx_compat,
174        body_def_id,
175        param_env,
176        assumed_wf_types,
177        // Don't *disable* the implied bounds hack; though this will only apply
178        // the implied bounds hack if this contains `bevy_ecs`'s `ParamSet` type.
179        false,
180    );
181    let errors_compat = infcx_compat.resolve_regions_with_outlives_env(&outlives_env);
182    if errors_compat.is_empty() {
183        // FIXME: Once we fix bevy, this would be the place to insert a warning
184        // to upgrade bevy.
185        Ok(())
186    } else {
187        Err(infcx_compat.err_ctxt().report_region_errors(body_def_id, &errors_compat))
188    }
189}
190
191pub(super) fn check_well_formed(
192    tcx: TyCtxt<'_>,
193    def_id: LocalDefId,
194) -> Result<(), ErrorGuaranteed> {
195    let mut res = crate::check::check::check_item_type(tcx, def_id);
196
197    for param in &tcx.generics_of(def_id).own_params {
198        res = res.and(check_param_wf(tcx, param));
199    }
200
201    res
202}
203
204/// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
205/// well-formed, meaning that they do not require any constraints not declared in the struct
206/// definition itself. For example, this definition would be illegal:
207///
208/// ```rust
209/// struct StaticRef<T> { x: &'static T }
210/// ```
211///
212/// because the type did not declare that `T: 'static`.
213///
214/// We do this check as a pre-pass before checking fn bodies because if these constraints are
215/// not included it frequently leads to confusing errors in fn bodies. So it's better to check
216/// the types first.
217#[instrument(skip(tcx), level = "debug")]
218pub(super) fn check_item<'tcx>(
219    tcx: TyCtxt<'tcx>,
220    item: &'tcx hir::Item<'tcx>,
221) -> Result<(), ErrorGuaranteed> {
222    let def_id = item.owner_id.def_id;
223
224    debug!(
225        ?item.owner_id,
226        item.name = ? tcx.def_path_str(def_id)
227    );
228
229    match item.kind {
230        // Right now we check that every default trait implementation
231        // has an implementation of itself. Basically, a case like:
232        //
233        //     impl Trait for T {}
234        //
235        // has a requirement of `T: Trait` which was required for default
236        // method implementations. Although this could be improved now that
237        // there's a better infrastructure in place for this, it's being left
238        // for a follow-up work.
239        //
240        // Since there's such a requirement, we need to check *just* positive
241        // implementations, otherwise things like:
242        //
243        //     impl !Send for T {}
244        //
245        // won't be allowed unless there's an *explicit* implementation of `Send`
246        // for `T`
247        hir::ItemKind::Impl(ref impl_) => {
248            crate::impl_wf_check::check_impl_wf(tcx, def_id)?;
249            let mut res = Ok(());
250            if let Some(of_trait) = impl_.of_trait {
251                let header = tcx.impl_trait_header(def_id).unwrap();
252                let is_auto = tcx.trait_is_auto(header.trait_ref.skip_binder().def_id);
253                if let (hir::Defaultness::Default { .. }, true) = (of_trait.defaultness, is_auto) {
254                    let sp = of_trait.trait_ref.path.span;
255                    res = Err(tcx
256                        .dcx()
257                        .struct_span_err(sp, "impls of auto traits cannot be default")
258                        .with_span_labels(of_trait.defaultness_span, "default because of this")
259                        .with_span_label(sp, "auto trait")
260                        .emit());
261                }
262                match header.polarity {
263                    ty::ImplPolarity::Positive => {
264                        res = res.and(check_impl(tcx, item, impl_));
265                    }
266                    ty::ImplPolarity::Negative => {
267                        let ast::ImplPolarity::Negative(span) = of_trait.polarity else {
268                            bug!("impl_polarity query disagrees with impl's polarity in HIR");
269                        };
270                        // FIXME(#27579): what amount of WF checking do we need for neg impls?
271                        if let hir::Defaultness::Default { .. } = of_trait.defaultness {
272                            let mut spans = vec![span];
273                            spans.extend(of_trait.defaultness_span);
274                            res = Err(struct_span_code_err!(
275                                tcx.dcx(),
276                                spans,
277                                E0750,
278                                "negative impls cannot be default impls"
279                            )
280                            .emit());
281                        }
282                    }
283                    ty::ImplPolarity::Reservation => {
284                        // FIXME: what amount of WF checking do we need for reservation impls?
285                    }
286                }
287            } else {
288                res = res.and(check_impl(tcx, item, impl_));
289            }
290            res
291        }
292        hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
293        hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
294        hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
295        hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
296        hir::ItemKind::Trait(..) => check_trait(tcx, item),
297        hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
298        _ => Ok(()),
299    }
300}
301
302pub(super) fn check_foreign_item<'tcx>(
303    tcx: TyCtxt<'tcx>,
304    item: &'tcx hir::ForeignItem<'tcx>,
305) -> Result<(), ErrorGuaranteed> {
306    let def_id = item.owner_id.def_id;
307
308    debug!(
309        ?item.owner_id,
310        item.name = ? tcx.def_path_str(def_id)
311    );
312
313    match item.kind {
314        hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
315        hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
316    }
317}
318
319pub(crate) fn check_trait_item<'tcx>(
320    tcx: TyCtxt<'tcx>,
321    def_id: LocalDefId,
322) -> Result<(), ErrorGuaranteed> {
323    // Check that an item definition in a subtrait is shadowing a supertrait item.
324    lint_item_shadowing_supertrait_item(tcx, def_id);
325
326    let mut res = Ok(());
327
328    if matches!(tcx.def_kind(def_id), DefKind::AssocFn) {
329        for &assoc_ty_def_id in
330            tcx.associated_types_for_impl_traits_in_associated_fn(def_id.to_def_id())
331        {
332            res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
333        }
334    }
335    res
336}
337
338/// Require that the user writes where clauses on GATs for the implicit
339/// outlives bounds involving trait parameters in trait functions and
340/// lifetimes passed as GAT args. See `self-outlives-lint` test.
341///
342/// We use the following trait as an example throughout this function:
343/// ```rust,ignore (this code fails due to this lint)
344/// trait IntoIter {
345///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
346///     type Item<'a>;
347///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
348/// }
349/// ```
350fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
351    // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
352    let mut required_bounds_by_item = FxIndexMap::default();
353    let associated_items = tcx.associated_items(trait_def_id);
354
355    // Loop over all GATs together, because if this lint suggests adding a where-clause bound
356    // to one GAT, it might then require us to an additional bound on another GAT.
357    // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
358    // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
359    // those GATs.
360    loop {
361        let mut should_continue = false;
362        for gat_item in associated_items.in_definition_order() {
363            let gat_def_id = gat_item.def_id.expect_local();
364            let gat_item = tcx.associated_item(gat_def_id);
365            // If this item is not an assoc ty, or has no args, then it's not a GAT
366            if !gat_item.is_type() {
367                continue;
368            }
369            let gat_generics = tcx.generics_of(gat_def_id);
370            // FIXME(jackh726): we can also warn in the more general case
371            if gat_generics.is_own_empty() {
372                continue;
373            }
374
375            // Gather the bounds with which all other items inside of this trait constrain the GAT.
376            // This is calculated by taking the intersection of the bounds that each item
377            // constrains the GAT with individually.
378            let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
379            for item in associated_items.in_definition_order() {
380                let item_def_id = item.def_id.expect_local();
381                // Skip our own GAT, since it does not constrain itself at all.
382                if item_def_id == gat_def_id {
383                    continue;
384                }
385
386                let param_env = tcx.param_env(item_def_id);
387
388                let item_required_bounds = match tcx.associated_item(item_def_id).kind {
389                    // In our example, this corresponds to `into_iter` method
390                    ty::AssocKind::Fn { .. } => {
391                        // For methods, we check the function signature's return type for any GATs
392                        // to constrain. In the `into_iter` case, we see that the return type
393                        // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
394                        let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
395                            item_def_id.to_def_id(),
396                            tcx.fn_sig(item_def_id).instantiate_identity(),
397                        );
398                        gather_gat_bounds(
399                            tcx,
400                            param_env,
401                            item_def_id,
402                            sig.inputs_and_output,
403                            // We also assume that all of the function signature's parameter types
404                            // are well formed.
405                            &sig.inputs().iter().copied().collect(),
406                            gat_def_id,
407                            gat_generics,
408                        )
409                    }
410                    // In our example, this corresponds to the `Iter` and `Item` associated types
411                    ty::AssocKind::Type { .. } => {
412                        // If our associated item is a GAT with missing bounds, add them to
413                        // the param-env here. This allows this GAT to propagate missing bounds
414                        // to other GATs.
415                        let param_env = augment_param_env(
416                            tcx,
417                            param_env,
418                            required_bounds_by_item.get(&item_def_id),
419                        );
420                        gather_gat_bounds(
421                            tcx,
422                            param_env,
423                            item_def_id,
424                            tcx.explicit_item_bounds(item_def_id)
425                                .iter_identity_copied()
426                                .collect::<Vec<_>>(),
427                            &FxIndexSet::default(),
428                            gat_def_id,
429                            gat_generics,
430                        )
431                    }
432                    ty::AssocKind::Const { .. } => None,
433                };
434
435                if let Some(item_required_bounds) = item_required_bounds {
436                    // Take the intersection of the required bounds for this GAT, and
437                    // the item_required_bounds which are the ones implied by just
438                    // this item alone.
439                    // This is why we use an Option<_>, since we need to distinguish
440                    // the empty set of bounds from the _uninitialized_ set of bounds.
441                    if let Some(new_required_bounds) = &mut new_required_bounds {
442                        new_required_bounds.retain(|b| item_required_bounds.contains(b));
443                    } else {
444                        new_required_bounds = Some(item_required_bounds);
445                    }
446                }
447            }
448
449            if let Some(new_required_bounds) = new_required_bounds {
450                let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
451                if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
452                    // Iterate until our required_bounds no longer change
453                    // Since they changed here, we should continue the loop
454                    should_continue = true;
455                }
456            }
457        }
458        // We know that this loop will eventually halt, since we only set `should_continue` if the
459        // `required_bounds` for this item grows. Since we are not creating any new region or type
460        // variables, the set of all region and type bounds that we could ever insert are limited
461        // by the number of unique types and regions we observe in a given item.
462        if !should_continue {
463            break;
464        }
465    }
466
467    for (gat_def_id, required_bounds) in required_bounds_by_item {
468        // Don't suggest adding `Self: 'a` to a GAT that can't be named
469        if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
470            continue;
471        }
472
473        let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
474        debug!(?required_bounds);
475        let param_env = tcx.param_env(gat_def_id);
476
477        let unsatisfied_bounds: Vec<_> = required_bounds
478            .into_iter()
479            .filter(|clause| match clause.kind().skip_binder() {
480                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
481                    !region_known_to_outlive(
482                        tcx,
483                        gat_def_id,
484                        param_env,
485                        &FxIndexSet::default(),
486                        a,
487                        b,
488                    )
489                }
490                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
491                    !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
492                }
493                _ => bug!("Unexpected ClauseKind"),
494            })
495            .map(|clause| clause.to_string())
496            .collect();
497
498        if !unsatisfied_bounds.is_empty() {
499            let plural = pluralize!(unsatisfied_bounds.len());
500            let suggestion = format!(
501                "{} {}",
502                gat_item_hir.generics.add_where_or_trailing_comma(),
503                unsatisfied_bounds.join(", "),
504            );
505            let bound =
506                if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
507            tcx.dcx()
508                .struct_span_err(
509                    gat_item_hir.span,
510                    format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
511                )
512                .with_span_suggestion(
513                    gat_item_hir.generics.tail_span_for_predicate_suggestion(),
514                    format!("add the required where clause{plural}"),
515                    suggestion,
516                    Applicability::MachineApplicable,
517                )
518                .with_note(format!(
519                    "{bound} currently required to ensure that impls have maximum flexibility"
520                ))
521                .with_note(
522                    "we are soliciting feedback, see issue #87479 \
523                     <https://github.com/rust-lang/rust/issues/87479> for more information",
524                )
525                .emit();
526        }
527    }
528}
529
530/// Add a new set of predicates to the caller_bounds of an existing param_env.
531fn augment_param_env<'tcx>(
532    tcx: TyCtxt<'tcx>,
533    param_env: ty::ParamEnv<'tcx>,
534    new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
535) -> ty::ParamEnv<'tcx> {
536    let Some(new_predicates) = new_predicates else {
537        return param_env;
538    };
539
540    if new_predicates.is_empty() {
541        return param_env;
542    }
543
544    let bounds = tcx.mk_clauses_from_iter(
545        param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
546    );
547    // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
548    // i.e. traits::normalize_param_env_or_error
549    ty::ParamEnv::new(bounds)
550}
551
552/// We use the following trait as an example throughout this function.
553/// Specifically, let's assume that `to_check` here is the return type
554/// of `into_iter`, and the GAT we are checking this for is `Iter`.
555/// ```rust,ignore (this code fails due to this lint)
556/// trait IntoIter {
557///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
558///     type Item<'a>;
559///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
560/// }
561/// ```
562fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
563    tcx: TyCtxt<'tcx>,
564    param_env: ty::ParamEnv<'tcx>,
565    item_def_id: LocalDefId,
566    to_check: T,
567    wf_tys: &FxIndexSet<Ty<'tcx>>,
568    gat_def_id: LocalDefId,
569    gat_generics: &'tcx ty::Generics,
570) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
571    // The bounds we that we would require from `to_check`
572    let mut bounds = FxIndexSet::default();
573
574    let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
575
576    // If both regions and types are empty, then this GAT isn't in the
577    // set of types we are checking, and we shouldn't try to do clause analysis
578    // (particularly, doing so would end up with an empty set of clauses,
579    // since the current method would require none, and we take the
580    // intersection of requirements of all methods)
581    if types.is_empty() && regions.is_empty() {
582        return None;
583    }
584
585    for (region_a, region_a_idx) in &regions {
586        // Ignore `'static` lifetimes for the purpose of this lint: it's
587        // because we know it outlives everything and so doesn't give meaningful
588        // clues. Also ignore `ReError`, to avoid knock-down errors.
589        if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
590            continue;
591        }
592        // For each region argument (e.g., `'a` in our example), check for a
593        // relationship to the type arguments (e.g., `Self`). If there is an
594        // outlives relationship (`Self: 'a`), then we want to ensure that is
595        // reflected in a where clause on the GAT itself.
596        for (ty, ty_idx) in &types {
597            // In our example, requires that `Self: 'a`
598            if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
599                debug!(?ty_idx, ?region_a_idx);
600                debug!("required clause: {ty} must outlive {region_a}");
601                // Translate into the generic parameters of the GAT. In
602                // our example, the type was `Self`, which will also be
603                // `Self` in the GAT.
604                let ty_param = gat_generics.param_at(*ty_idx, tcx);
605                let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
606                // Same for the region. In our example, 'a corresponds
607                // to the 'me parameter.
608                let region_param = gat_generics.param_at(*region_a_idx, tcx);
609                let region_param = ty::Region::new_early_param(
610                    tcx,
611                    ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
612                );
613                // The predicate we expect to see. (In our example,
614                // `Self: 'me`.)
615                bounds.insert(
616                    ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
617                        .upcast(tcx),
618                );
619            }
620        }
621
622        // For each region argument (e.g., `'a` in our example), also check for a
623        // relationship to the other region arguments. If there is an outlives
624        // relationship, then we want to ensure that is reflected in the where clause
625        // on the GAT itself.
626        for (region_b, region_b_idx) in &regions {
627            // Again, skip `'static` because it outlives everything. Also, we trivially
628            // know that a region outlives itself. Also ignore `ReError`, to avoid
629            // knock-down errors.
630            if matches!(region_b.kind(), ty::ReStatic | ty::ReError(_)) || region_a == region_b {
631                continue;
632            }
633            if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
634                debug!(?region_a_idx, ?region_b_idx);
635                debug!("required clause: {region_a} must outlive {region_b}");
636                // Translate into the generic parameters of the GAT.
637                let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
638                let region_a_param = ty::Region::new_early_param(
639                    tcx,
640                    ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
641                );
642                // Same for the region.
643                let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
644                let region_b_param = ty::Region::new_early_param(
645                    tcx,
646                    ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
647                );
648                // The predicate we expect to see.
649                bounds.insert(
650                    ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
651                        region_a_param,
652                        region_b_param,
653                    ))
654                    .upcast(tcx),
655                );
656            }
657        }
658    }
659
660    Some(bounds)
661}
662
663/// Given a known `param_env` and a set of well formed types, can we prove that
664/// `ty` outlives `region`.
665fn ty_known_to_outlive<'tcx>(
666    tcx: TyCtxt<'tcx>,
667    id: LocalDefId,
668    param_env: ty::ParamEnv<'tcx>,
669    wf_tys: &FxIndexSet<Ty<'tcx>>,
670    ty: Ty<'tcx>,
671    region: ty::Region<'tcx>,
672) -> bool {
673    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
674        infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
675            sub_region: region,
676            sup_type: ty,
677            origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
678        });
679    })
680}
681
682/// Given a known `param_env` and a set of well formed types, can we prove that
683/// `region_a` outlives `region_b`
684fn region_known_to_outlive<'tcx>(
685    tcx: TyCtxt<'tcx>,
686    id: LocalDefId,
687    param_env: ty::ParamEnv<'tcx>,
688    wf_tys: &FxIndexSet<Ty<'tcx>>,
689    region_a: ty::Region<'tcx>,
690    region_b: ty::Region<'tcx>,
691) -> bool {
692    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
693        infcx.sub_regions(
694            SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
695            region_b,
696            region_a,
697        );
698    })
699}
700
701/// Given a known `param_env` and a set of well formed types, set up an
702/// `InferCtxt`, call the passed function (to e.g. set up region constraints
703/// to be tested), then resolve region and return errors
704fn test_region_obligations<'tcx>(
705    tcx: TyCtxt<'tcx>,
706    id: LocalDefId,
707    param_env: ty::ParamEnv<'tcx>,
708    wf_tys: &FxIndexSet<Ty<'tcx>>,
709    add_constraints: impl FnOnce(&InferCtxt<'tcx>),
710) -> bool {
711    // Unfortunately, we have to use a new `InferCtxt` each call, because
712    // region constraints get added and solved there and we need to test each
713    // call individually.
714    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
715
716    add_constraints(&infcx);
717
718    let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
719    debug!(?errors, "errors");
720
721    // If we were able to prove that the type outlives the region without
722    // an error, it must be because of the implied or explicit bounds...
723    errors.is_empty()
724}
725
726/// TypeVisitor that looks for uses of GATs like
727/// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
728/// the two vectors, `regions` and `types` (depending on their kind). For each
729/// parameter `Pi` also track the index `i`.
730struct GATArgsCollector<'tcx> {
731    gat: DefId,
732    // Which region appears and which parameter index its instantiated with
733    regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
734    // Which params appears and which parameter index its instantiated with
735    types: FxIndexSet<(Ty<'tcx>, usize)>,
736}
737
738impl<'tcx> GATArgsCollector<'tcx> {
739    fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
740        gat: DefId,
741        t: T,
742    ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
743        let mut visitor =
744            GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
745        t.visit_with(&mut visitor);
746        (visitor.regions, visitor.types)
747    }
748}
749
750impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
751    fn visit_ty(&mut self, t: Ty<'tcx>) {
752        match t.kind() {
753            ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
754                for (idx, arg) in p.args.iter().enumerate() {
755                    match arg.kind() {
756                        GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
757                            self.regions.insert((lt, idx));
758                        }
759                        GenericArgKind::Type(t) => {
760                            self.types.insert((t, idx));
761                        }
762                        _ => {}
763                    }
764                }
765            }
766            _ => {}
767        }
768        t.super_visit_with(self)
769    }
770}
771
772fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
773    let item_name = tcx.item_name(trait_item_def_id.to_def_id());
774    let trait_def_id = tcx.local_parent(trait_item_def_id);
775
776    let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
777        .skip(1)
778        .flat_map(|supertrait_def_id| {
779            tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
780        })
781        .collect();
782    if !shadowed.is_empty() {
783        let shadowee = if let [shadowed] = shadowed[..] {
784            errors::SupertraitItemShadowee::Labeled {
785                span: tcx.def_span(shadowed.def_id),
786                supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
787            }
788        } else {
789            let (traits, spans): (Vec<_>, Vec<_>) = shadowed
790                .iter()
791                .map(|item| {
792                    (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
793                })
794                .unzip();
795            errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
796        };
797
798        tcx.emit_node_span_lint(
799            SUPERTRAIT_ITEM_SHADOWING_DEFINITION,
800            tcx.local_def_id_to_hir_id(trait_item_def_id),
801            tcx.def_span(trait_item_def_id),
802            errors::SupertraitItemShadowing {
803                item: item_name,
804                subtrait: tcx.item_name(trait_def_id.to_def_id()),
805                shadowee,
806            },
807        );
808    }
809}
810
811fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
812    match param.kind {
813        // We currently only check wf of const params here.
814        ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
815
816        // Const parameters are well formed if their type is structural match.
817        ty::GenericParamDefKind::Const { .. } => {
818            let ty = tcx.type_of(param.def_id).instantiate_identity();
819            let span = tcx.def_span(param.def_id);
820            let def_id = param.def_id.expect_local();
821
822            if tcx.features().adt_const_params() {
823                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
824                    wfcx.register_bound(
825                        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
826                        wfcx.param_env,
827                        ty,
828                        tcx.require_lang_item(LangItem::ConstParamTy, span),
829                    );
830                    Ok(())
831                })
832            } else {
833                let span = || {
834                    let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
835                        tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
836                    else {
837                        bug!()
838                    };
839                    span
840                };
841                let mut diag = match ty.kind() {
842                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
843                    ty::FnPtr(..) => tcx.dcx().struct_span_err(
844                        span(),
845                        "using function pointers as const generic parameters is forbidden",
846                    ),
847                    ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
848                        span(),
849                        "using raw pointers as const generic parameters is forbidden",
850                    ),
851                    _ => {
852                        // Avoid showing "{type error}" to users. See #118179.
853                        ty.error_reported()?;
854
855                        tcx.dcx().struct_span_err(
856                            span(),
857                            format!(
858                                "`{ty}` is forbidden as the type of a const generic parameter",
859                            ),
860                        )
861                    }
862                };
863
864                diag.note("the only supported types are integers, `bool`, and `char`");
865
866                let cause = ObligationCause::misc(span(), def_id);
867                let adt_const_params_feature_string =
868                    " more complex and user defined types".to_string();
869                let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
870                    tcx,
871                    tcx.param_env(param.def_id),
872                    ty,
873                    cause,
874                ) {
875                    // Can never implement `ConstParamTy`, don't suggest anything.
876                    Err(
877                        ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
878                        | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
879                    ) => None,
880                    Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
881                        Some(vec![
882                            (adt_const_params_feature_string, sym::adt_const_params),
883                            (
884                                " references to implement the `ConstParamTy` trait".into(),
885                                sym::unsized_const_params,
886                            ),
887                        ])
888                    }
889                    // May be able to implement `ConstParamTy`. Only emit the feature help
890                    // if the type is local, since the user may be able to fix the local type.
891                    Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
892                        fn ty_is_local(ty: Ty<'_>) -> bool {
893                            match ty.kind() {
894                                ty::Adt(adt_def, ..) => adt_def.did().is_local(),
895                                // Arrays and slices use the inner type's `ConstParamTy`.
896                                ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
897                                // `&` references use the inner type's `ConstParamTy`.
898                                // `&mut` are not supported.
899                                ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
900                                // Say that a tuple is local if any of its components are local.
901                                // This is not strictly correct, but it's likely that the user can fix the local component.
902                                ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
903                                _ => false,
904                            }
905                        }
906
907                        ty_is_local(ty).then_some(vec![(
908                            adt_const_params_feature_string,
909                            sym::adt_const_params,
910                        )])
911                    }
912                    // Implements `ConstParamTy`, suggest adding the feature to enable.
913                    Ok(..) => Some(vec![(adt_const_params_feature_string, sym::adt_const_params)]),
914                };
915                if let Some(features) = may_suggest_feature {
916                    tcx.disabled_nightly_features(&mut diag, features);
917                }
918
919                Err(diag.emit())
920            }
921        }
922    }
923}
924
925#[instrument(level = "debug", skip(tcx))]
926pub(crate) fn check_associated_item(
927    tcx: TyCtxt<'_>,
928    item_id: LocalDefId,
929) -> Result<(), ErrorGuaranteed> {
930    let loc = Some(WellFormedLoc::Ty(item_id));
931    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
932        let item = tcx.associated_item(item_id);
933
934        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
935        // other `Foo` impls are incoherent.
936        tcx.ensure_ok().coherent_trait(tcx.parent(item.trait_item_or_self()?))?;
937
938        let self_ty = match item.container {
939            ty::AssocContainer::Trait => tcx.types.self_param,
940            ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
941                tcx.type_of(item.container_id(tcx)).instantiate_identity()
942            }
943        };
944
945        let span = tcx.def_span(item_id);
946
947        match item.kind {
948            ty::AssocKind::Const { .. } => {
949                let ty = tcx.type_of(item.def_id).instantiate_identity();
950                let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
951                wfcx.register_wf_obligation(span, loc, ty.into());
952                check_sized_if_body(
953                    wfcx,
954                    item.def_id.expect_local(),
955                    ty,
956                    Some(span),
957                    ObligationCauseCode::SizedConstOrStatic,
958                );
959                Ok(())
960            }
961            ty::AssocKind::Fn { .. } => {
962                let sig = tcx.fn_sig(item.def_id).instantiate_identity();
963                let hir_sig =
964                    tcx.hir_node_by_def_id(item_id).fn_sig().expect("bad signature for method");
965                check_fn_or_method(wfcx, sig, hir_sig.decl, item_id);
966                check_method_receiver(wfcx, hir_sig, item, self_ty)
967            }
968            ty::AssocKind::Type { .. } => {
969                if let ty::AssocContainer::Trait = item.container {
970                    check_associated_type_bounds(wfcx, item, span)
971                }
972                if item.defaultness(tcx).has_value() {
973                    let ty = tcx.type_of(item.def_id).instantiate_identity();
974                    let ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
975                    wfcx.register_wf_obligation(span, loc, ty.into());
976                }
977                Ok(())
978            }
979        }
980    })
981}
982
983/// In a type definition, we check that to ensure that the types of the fields are well-formed.
984fn check_type_defn<'tcx>(
985    tcx: TyCtxt<'tcx>,
986    item: &hir::Item<'tcx>,
987    all_sized: bool,
988) -> Result<(), ErrorGuaranteed> {
989    let _ = tcx.representability(item.owner_id.def_id);
990    let adt_def = tcx.adt_def(item.owner_id);
991
992    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
993        let variants = adt_def.variants();
994        let packed = adt_def.repr().packed();
995
996        for variant in variants.iter() {
997            // All field types must be well-formed.
998            for field in &variant.fields {
999                if let Some(def_id) = field.value
1000                    && let Some(_ty) = tcx.type_of(def_id).no_bound_vars()
1001                {
1002                    // FIXME(generic_const_exprs, default_field_values): this is a hack and needs to
1003                    // be refactored to check the instantiate-ability of the code better.
1004                    if let Some(def_id) = def_id.as_local()
1005                        && let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
1006                        && let expr = &tcx.hir_body(anon.body).value
1007                        && let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1008                        && let Res::Def(DefKind::ConstParam, _def_id) = path.res
1009                    {
1010                        // Do not evaluate bare `const` params, as those would ICE and are only
1011                        // usable if `#![feature(generic_const_exprs)]` is enabled.
1012                    } else {
1013                        // Evaluate the constant proactively, to emit an error if the constant has
1014                        // an unconditional error. We only do so if the const has no type params.
1015                        let _ = tcx.const_eval_poly(def_id);
1016                    }
1017                }
1018                let field_id = field.did.expect_local();
1019                let hir::FieldDef { ty: hir_ty, .. } =
1020                    tcx.hir_node_by_def_id(field_id).expect_field();
1021                let ty = wfcx.deeply_normalize(
1022                    hir_ty.span,
1023                    None,
1024                    tcx.type_of(field.did).instantiate_identity(),
1025                );
1026                wfcx.register_wf_obligation(
1027                    hir_ty.span,
1028                    Some(WellFormedLoc::Ty(field_id)),
1029                    ty.into(),
1030                )
1031            }
1032
1033            // For DST, or when drop needs to copy things around, all
1034            // intermediate types must be sized.
1035            let needs_drop_copy = || {
1036                packed && {
1037                    let ty = tcx.type_of(variant.tail().did).instantiate_identity();
1038                    let ty = tcx.erase_and_anonymize_regions(ty);
1039                    assert!(!ty.has_infer());
1040                    ty.needs_drop(tcx, wfcx.infcx.typing_env(wfcx.param_env))
1041                }
1042            };
1043            // All fields (except for possibly the last) should be sized.
1044            let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1045            let unsized_len = if all_sized { 0 } else { 1 };
1046            for (idx, field) in
1047                variant.fields.raw[..variant.fields.len() - unsized_len].iter().enumerate()
1048            {
1049                let last = idx == variant.fields.len() - 1;
1050                let field_id = field.did.expect_local();
1051                let hir::FieldDef { ty: hir_ty, .. } =
1052                    tcx.hir_node_by_def_id(field_id).expect_field();
1053                let ty = wfcx.normalize(
1054                    hir_ty.span,
1055                    None,
1056                    tcx.type_of(field.did).instantiate_identity(),
1057                );
1058                wfcx.register_bound(
1059                    traits::ObligationCause::new(
1060                        hir_ty.span,
1061                        wfcx.body_def_id,
1062                        ObligationCauseCode::FieldSized {
1063                            adt_kind: match &item.kind {
1064                                ItemKind::Struct(..) => AdtKind::Struct,
1065                                ItemKind::Union(..) => AdtKind::Union,
1066                                ItemKind::Enum(..) => AdtKind::Enum,
1067                                kind => span_bug!(
1068                                    item.span,
1069                                    "should be wfchecking an ADT, got {kind:?}"
1070                                ),
1071                            },
1072                            span: hir_ty.span,
1073                            last,
1074                        },
1075                    ),
1076                    wfcx.param_env,
1077                    ty,
1078                    tcx.require_lang_item(LangItem::Sized, hir_ty.span),
1079                );
1080            }
1081
1082            // Explicit `enum` discriminant values must const-evaluate successfully.
1083            if let ty::VariantDiscr::Explicit(discr_def_id) = variant.discr {
1084                match tcx.const_eval_poly(discr_def_id) {
1085                    Ok(_) => {}
1086                    Err(ErrorHandled::Reported(..)) => {}
1087                    Err(ErrorHandled::TooGeneric(sp)) => {
1088                        span_bug!(sp, "enum variant discr was too generic to eval")
1089                    }
1090                }
1091            }
1092        }
1093
1094        check_where_clauses(wfcx, item.owner_id.def_id);
1095        Ok(())
1096    })
1097}
1098
1099#[instrument(skip(tcx, item))]
1100fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) -> Result<(), ErrorGuaranteed> {
1101    debug!(?item.owner_id);
1102
1103    let def_id = item.owner_id.def_id;
1104    if tcx.is_lang_item(def_id.into(), LangItem::PointeeSized) {
1105        // `PointeeSized` is removed during lowering.
1106        return Ok(());
1107    }
1108
1109    let trait_def = tcx.trait_def(def_id);
1110    if trait_def.is_marker
1111        || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1112    {
1113        for associated_def_id in &*tcx.associated_item_def_ids(def_id) {
1114            struct_span_code_err!(
1115                tcx.dcx(),
1116                tcx.def_span(*associated_def_id),
1117                E0714,
1118                "marker traits cannot have associated items",
1119            )
1120            .emit();
1121        }
1122    }
1123
1124    let res = enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1125        check_where_clauses(wfcx, def_id);
1126        Ok(())
1127    });
1128
1129    // Only check traits, don't check trait aliases
1130    if let hir::ItemKind::Trait(..) = item.kind {
1131        check_gat_where_clauses(tcx, item.owner_id.def_id);
1132    }
1133    res
1134}
1135
1136/// Checks all associated type defaults of trait `trait_def_id`.
1137///
1138/// Assuming the defaults are used, check that all predicates (bounds on the
1139/// assoc type and where clauses on the trait) hold.
1140fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocItem, span: Span) {
1141    let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1142
1143    debug!("check_associated_type_bounds: bounds={:?}", bounds);
1144    let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
1145        let normalized_bound = wfcx.normalize(span, None, bound);
1146        traits::wf::clause_obligations(
1147            wfcx.infcx,
1148            wfcx.param_env,
1149            wfcx.body_def_id,
1150            normalized_bound,
1151            bound_span,
1152        )
1153    });
1154
1155    wfcx.register_obligations(wf_obligations);
1156}
1157
1158fn check_item_fn(
1159    tcx: TyCtxt<'_>,
1160    def_id: LocalDefId,
1161    decl: &hir::FnDecl<'_>,
1162) -> Result<(), ErrorGuaranteed> {
1163    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1164        let sig = tcx.fn_sig(def_id).instantiate_identity();
1165        check_fn_or_method(wfcx, sig, decl, def_id);
1166        Ok(())
1167    })
1168}
1169
1170#[instrument(level = "debug", skip(tcx))]
1171pub(crate) fn check_static_item<'tcx>(
1172    tcx: TyCtxt<'tcx>,
1173    item_id: LocalDefId,
1174    ty: Ty<'tcx>,
1175    should_check_for_sync: bool,
1176) -> Result<(), ErrorGuaranteed> {
1177    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1178        let span = tcx.ty_span(item_id);
1179        let item_ty = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1180
1181        let is_foreign_item = tcx.is_foreign_item(item_id);
1182
1183        let forbid_unsized = !is_foreign_item || {
1184            let tail = tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1185            !matches!(tail.kind(), ty::Foreign(_))
1186        };
1187
1188        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1189        if forbid_unsized {
1190            let span = tcx.def_span(item_id);
1191            wfcx.register_bound(
1192                traits::ObligationCause::new(
1193                    span,
1194                    wfcx.body_def_id,
1195                    ObligationCauseCode::SizedConstOrStatic,
1196                ),
1197                wfcx.param_env,
1198                item_ty,
1199                tcx.require_lang_item(LangItem::Sized, span),
1200            );
1201        }
1202
1203        // Ensure that the end result is `Sync` in a non-thread local `static`.
1204        let should_check_for_sync = should_check_for_sync
1205            && !is_foreign_item
1206            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1207            && !tcx.is_thread_local_static(item_id.to_def_id());
1208
1209        if should_check_for_sync {
1210            wfcx.register_bound(
1211                traits::ObligationCause::new(
1212                    span,
1213                    wfcx.body_def_id,
1214                    ObligationCauseCode::SharedStatic,
1215                ),
1216                wfcx.param_env,
1217                item_ty,
1218                tcx.require_lang_item(LangItem::Sync, span),
1219            );
1220        }
1221        Ok(())
1222    })
1223}
1224
1225pub(crate) fn check_const_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
1226    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1227        let ty = tcx.type_of(def_id).instantiate_identity();
1228        let ty_span = tcx.ty_span(def_id);
1229        let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
1230
1231        wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
1232        wfcx.register_bound(
1233            traits::ObligationCause::new(
1234                ty_span,
1235                wfcx.body_def_id,
1236                ObligationCauseCode::SizedConstOrStatic,
1237            ),
1238            wfcx.param_env,
1239            ty,
1240            tcx.require_lang_item(LangItem::Sized, ty_span),
1241        );
1242
1243        check_where_clauses(wfcx, def_id);
1244
1245        Ok(())
1246    })
1247}
1248
1249#[instrument(level = "debug", skip(tcx, impl_))]
1250fn check_impl<'tcx>(
1251    tcx: TyCtxt<'tcx>,
1252    item: &'tcx hir::Item<'tcx>,
1253    impl_: &hir::Impl<'_>,
1254) -> Result<(), ErrorGuaranteed> {
1255    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1256        match impl_.of_trait {
1257            Some(of_trait) => {
1258                // `#[rustc_reservation_impl]` impls are not real impls and
1259                // therefore don't need to be WF (the trait's `Self: Trait` predicate
1260                // won't hold).
1261                let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1262                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
1263                // other `Foo` impls are incoherent.
1264                tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1265                let trait_span = of_trait.trait_ref.path.span;
1266                let trait_ref = wfcx.deeply_normalize(
1267                    trait_span,
1268                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1269                    trait_ref,
1270                );
1271                let trait_pred =
1272                    ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1273                let mut obligations = traits::wf::trait_obligations(
1274                    wfcx.infcx,
1275                    wfcx.param_env,
1276                    wfcx.body_def_id,
1277                    trait_pred,
1278                    trait_span,
1279                    item,
1280                );
1281                for obligation in &mut obligations {
1282                    if obligation.cause.span != trait_span {
1283                        // We already have a better span.
1284                        continue;
1285                    }
1286                    if let Some(pred) = obligation.predicate.as_trait_clause()
1287                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1288                    {
1289                        obligation.cause.span = impl_.self_ty.span;
1290                    }
1291                    if let Some(pred) = obligation.predicate.as_projection_clause()
1292                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1293                    {
1294                        obligation.cause.span = impl_.self_ty.span;
1295                    }
1296                }
1297
1298                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1299                if tcx.is_conditionally_const(item.owner_id.def_id) {
1300                    for (bound, _) in
1301                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1302                    {
1303                        let bound = wfcx.normalize(
1304                            item.span,
1305                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1306                            bound,
1307                        );
1308                        wfcx.register_obligation(Obligation::new(
1309                            tcx,
1310                            ObligationCause::new(
1311                                impl_.self_ty.span,
1312                                wfcx.body_def_id,
1313                                ObligationCauseCode::WellFormed(None),
1314                            ),
1315                            wfcx.param_env,
1316                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1317                        ))
1318                    }
1319                }
1320
1321                debug!(?obligations);
1322                wfcx.register_obligations(obligations);
1323            }
1324            None => {
1325                let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1326                let self_ty = wfcx.deeply_normalize(
1327                    item.span,
1328                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1329                    self_ty,
1330                );
1331                wfcx.register_wf_obligation(
1332                    impl_.self_ty.span,
1333                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1334                    self_ty.into(),
1335                );
1336            }
1337        }
1338
1339        check_where_clauses(wfcx, item.owner_id.def_id);
1340        Ok(())
1341    })
1342}
1343
1344/// Checks where-clauses and inline bounds that are declared on `def_id`.
1345#[instrument(level = "debug", skip(wfcx))]
1346pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1347    let infcx = wfcx.infcx;
1348    let tcx = wfcx.tcx();
1349
1350    let predicates = tcx.predicates_of(def_id.to_def_id());
1351    let generics = tcx.generics_of(def_id);
1352
1353    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1354    // For example, this forbids the declaration:
1355    //
1356    //     struct Foo<T = Vec<[u32]>> { .. }
1357    //
1358    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1359    for param in &generics.own_params {
1360        if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1361            // Ignore dependent defaults -- that is, where the default of one type
1362            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1363            // be sure if it will error or not as user might always specify the other.
1364            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1365            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1366            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1367            if !default.has_param() {
1368                wfcx.register_wf_obligation(
1369                    tcx.def_span(param.def_id),
1370                    matches!(param.kind, GenericParamDefKind::Type { .. })
1371                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1372                    default.as_term().unwrap(),
1373                );
1374            } else {
1375                // If we've got a generic const parameter we still want to check its
1376                // type is correct in case both it and the param type are fully concrete.
1377                let GenericArgKind::Const(ct) = default.kind() else {
1378                    continue;
1379                };
1380
1381                let ct_ty = match ct.kind() {
1382                    ty::ConstKind::Infer(_)
1383                    | ty::ConstKind::Placeholder(_)
1384                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1385                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1386                    ty::ConstKind::Value(cv) => cv.ty,
1387                    ty::ConstKind::Unevaluated(uv) => {
1388                        infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1389                    }
1390                    ty::ConstKind::Param(param_ct) => {
1391                        param_ct.find_const_ty_from_env(wfcx.param_env)
1392                    }
1393                };
1394
1395                let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1396                if !ct_ty.has_param() && !param_ty.has_param() {
1397                    let cause = traits::ObligationCause::new(
1398                        tcx.def_span(param.def_id),
1399                        wfcx.body_def_id,
1400                        ObligationCauseCode::WellFormed(None),
1401                    );
1402                    wfcx.register_obligation(Obligation::new(
1403                        tcx,
1404                        cause,
1405                        wfcx.param_env,
1406                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1407                    ));
1408                }
1409            }
1410        }
1411    }
1412
1413    // Check that trait predicates are WF when params are instantiated with their defaults.
1414    // We don't want to overly constrain the predicates that may be written but we want to
1415    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1416    // Therefore we check if a predicate which contains a single type param
1417    // with a concrete default is WF with that default instantiated.
1418    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1419    //
1420    // First we build the defaulted generic parameters.
1421    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1422        if param.index >= generics.parent_count as u32
1423            // If the param has a default, ...
1424            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1425            // ... and it's not a dependent default, ...
1426            && !default.has_param()
1427        {
1428            // ... then instantiate it with the default.
1429            return default;
1430        }
1431        tcx.mk_param_from_def(param)
1432    });
1433
1434    // Now we build the instantiated predicates.
1435    let default_obligations = predicates
1436        .predicates
1437        .iter()
1438        .flat_map(|&(pred, sp)| {
1439            #[derive(Default)]
1440            struct CountParams {
1441                params: FxHashSet<u32>,
1442            }
1443            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1444                type Result = ControlFlow<()>;
1445                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1446                    if let ty::Param(param) = t.kind() {
1447                        self.params.insert(param.index);
1448                    }
1449                    t.super_visit_with(self)
1450                }
1451
1452                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1453                    ControlFlow::Break(())
1454                }
1455
1456                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1457                    if let ty::ConstKind::Param(param) = c.kind() {
1458                        self.params.insert(param.index);
1459                    }
1460                    c.super_visit_with(self)
1461                }
1462            }
1463            let mut param_count = CountParams::default();
1464            let has_region = pred.visit_with(&mut param_count).is_break();
1465            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1466            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1467            // or preds with multiple params.
1468            if instantiated_pred.has_non_region_param()
1469                || param_count.params.len() > 1
1470                || has_region
1471            {
1472                None
1473            } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1474                // Avoid duplication of predicates that contain no parameters, for example.
1475                None
1476            } else {
1477                Some((instantiated_pred, sp))
1478            }
1479        })
1480        .map(|(pred, sp)| {
1481            // Convert each of those into an obligation. So if you have
1482            // something like `struct Foo<T: Copy = String>`, we would
1483            // take that predicate `T: Copy`, instantiated with `String: Copy`
1484            // (actually that happens in the previous `flat_map` call),
1485            // and then try to prove it (in this case, we'll fail).
1486            //
1487            // Note the subtle difference from how we handle `predicates`
1488            // below: there, we are not trying to prove those predicates
1489            // to be *true* but merely *well-formed*.
1490            let pred = wfcx.normalize(sp, None, pred);
1491            let cause = traits::ObligationCause::new(
1492                sp,
1493                wfcx.body_def_id,
1494                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1495            );
1496            Obligation::new(tcx, cause, wfcx.param_env, pred)
1497        });
1498
1499    let predicates = predicates.instantiate_identity(tcx);
1500
1501    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1502    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1503        let p = wfcx.normalize(sp, None, p);
1504        traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1505    });
1506    let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1507    wfcx.register_obligations(obligations);
1508}
1509
1510#[instrument(level = "debug", skip(wfcx, hir_decl))]
1511fn check_fn_or_method<'tcx>(
1512    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1513    sig: ty::PolyFnSig<'tcx>,
1514    hir_decl: &hir::FnDecl<'_>,
1515    def_id: LocalDefId,
1516) {
1517    let tcx = wfcx.tcx();
1518    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1519
1520    // Normalize the input and output types one at a time, using a different
1521    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1522    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1523    // for each type, preventing the HIR wf check from generating
1524    // a nice error message.
1525    let arg_span =
1526        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1527
1528    sig.inputs_and_output =
1529        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1530            wfcx.deeply_normalize(
1531                arg_span(idx),
1532                Some(WellFormedLoc::Param {
1533                    function: def_id,
1534                    // Note that the `param_idx` of the output type is
1535                    // one greater than the index of the last input type.
1536                    param_idx: idx,
1537                }),
1538                ty,
1539            )
1540        }));
1541
1542    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1543        wfcx.register_wf_obligation(
1544            arg_span(idx),
1545            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1546            ty.into(),
1547        );
1548    }
1549
1550    check_where_clauses(wfcx, def_id);
1551
1552    if sig.abi == ExternAbi::RustCall {
1553        let span = tcx.def_span(def_id);
1554        let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1555        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1556        // Check that the argument is a tuple and is sized
1557        if let Some(ty) = inputs.next() {
1558            wfcx.register_bound(
1559                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1560                wfcx.param_env,
1561                *ty,
1562                tcx.require_lang_item(hir::LangItem::Tuple, span),
1563            );
1564            wfcx.register_bound(
1565                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1566                wfcx.param_env,
1567                *ty,
1568                tcx.require_lang_item(hir::LangItem::Sized, span),
1569            );
1570        } else {
1571            tcx.dcx().span_err(
1572                hir_decl.inputs.last().map_or(span, |input| input.span),
1573                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1574            );
1575        }
1576        // No more inputs other than the `self` type and the tuple type
1577        if inputs.next().is_some() {
1578            tcx.dcx().span_err(
1579                hir_decl.inputs.last().map_or(span, |input| input.span),
1580                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1581            );
1582        }
1583    }
1584
1585    // If the function has a body, additionally require that the return type is sized.
1586    check_sized_if_body(
1587        wfcx,
1588        def_id,
1589        sig.output(),
1590        match hir_decl.output {
1591            hir::FnRetTy::Return(ty) => Some(ty.span),
1592            hir::FnRetTy::DefaultReturn(_) => None,
1593        },
1594        ObligationCauseCode::SizedReturnType,
1595    );
1596}
1597
1598fn check_sized_if_body<'tcx>(
1599    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1600    def_id: LocalDefId,
1601    ty: Ty<'tcx>,
1602    maybe_span: Option<Span>,
1603    code: ObligationCauseCode<'tcx>,
1604) {
1605    let tcx = wfcx.tcx();
1606    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1607        let span = maybe_span.unwrap_or(body.value.span);
1608
1609        wfcx.register_bound(
1610            ObligationCause::new(span, def_id, code),
1611            wfcx.param_env,
1612            ty,
1613            tcx.require_lang_item(LangItem::Sized, span),
1614        );
1615    }
1616}
1617
1618/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1619#[derive(Clone, Copy, PartialEq)]
1620enum ArbitrarySelfTypesLevel {
1621    Basic,        // just arbitrary_self_types
1622    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1623}
1624
1625#[instrument(level = "debug", skip(wfcx))]
1626fn check_method_receiver<'tcx>(
1627    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1628    fn_sig: &hir::FnSig<'_>,
1629    method: ty::AssocItem,
1630    self_ty: Ty<'tcx>,
1631) -> Result<(), ErrorGuaranteed> {
1632    let tcx = wfcx.tcx();
1633
1634    if !method.is_method() {
1635        return Ok(());
1636    }
1637
1638    let span = fn_sig.decl.inputs[0].span;
1639    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1640
1641    let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1642    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1643    let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1644
1645    debug!("check_method_receiver: sig={:?}", sig);
1646
1647    let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1648
1649    let receiver_ty = sig.inputs()[0];
1650    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1651
1652    // If the receiver already has errors reported, consider it valid to avoid
1653    // unnecessary errors (#58712).
1654    if receiver_ty.references_error() {
1655        return Ok(());
1656    }
1657
1658    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1659        Some(ArbitrarySelfTypesLevel::WithPointers)
1660    } else if tcx.features().arbitrary_self_types() {
1661        Some(ArbitrarySelfTypesLevel::Basic)
1662    } else {
1663        None
1664    };
1665    let generics = tcx.generics_of(method.def_id);
1666
1667    let receiver_validity =
1668        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1669    if let Err(receiver_validity_err) = receiver_validity {
1670        return Err(match arbitrary_self_types_level {
1671            // Wherever possible, emit a message advising folks that the features
1672            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1673            // have helped.
1674            None if receiver_is_valid(
1675                wfcx,
1676                span,
1677                receiver_ty,
1678                self_ty,
1679                Some(ArbitrarySelfTypesLevel::Basic),
1680                generics,
1681            )
1682            .is_ok() =>
1683            {
1684                // Report error; would have worked with `arbitrary_self_types`.
1685                feature_err(
1686                    &tcx.sess,
1687                    sym::arbitrary_self_types,
1688                    span,
1689                    format!(
1690                        "`{receiver_ty}` cannot be used as the type of `self` without \
1691                            the `arbitrary_self_types` feature",
1692                    ),
1693                )
1694                .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1695                .emit()
1696            }
1697            None | Some(ArbitrarySelfTypesLevel::Basic)
1698                if receiver_is_valid(
1699                    wfcx,
1700                    span,
1701                    receiver_ty,
1702                    self_ty,
1703                    Some(ArbitrarySelfTypesLevel::WithPointers),
1704                    generics,
1705                )
1706                .is_ok() =>
1707            {
1708                // Report error; would have worked with `arbitrary_self_types_pointers`.
1709                feature_err(
1710                    &tcx.sess,
1711                    sym::arbitrary_self_types_pointers,
1712                    span,
1713                    format!(
1714                        "`{receiver_ty}` cannot be used as the type of `self` without \
1715                            the `arbitrary_self_types_pointers` feature",
1716                    ),
1717                )
1718                .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1719                .emit()
1720            }
1721            _ =>
1722            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1723            {
1724                match receiver_validity_err {
1725                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1726                        let hint = match receiver_ty
1727                            .builtin_deref(false)
1728                            .unwrap_or(receiver_ty)
1729                            .ty_adt_def()
1730                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1731                        {
1732                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1733                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1734                            _ => None,
1735                        };
1736
1737                        tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1738                    }
1739                    ReceiverValidityError::DoesNotDeref => {
1740                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1741                            span,
1742                            receiver_ty,
1743                        })
1744                    }
1745                    ReceiverValidityError::MethodGenericParamUsed => {
1746                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1747                    }
1748                }
1749            }
1750        });
1751    }
1752    Ok(())
1753}
1754
1755/// Error cases which may be returned from `receiver_is_valid`. These error
1756/// cases are generated in this function as they may be unearthed as we explore
1757/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1758enum ReceiverValidityError {
1759    /// The self type does not get to the receiver type by following the
1760    /// autoderef chain.
1761    DoesNotDeref,
1762    /// A type was found which is a method type parameter, and that's not allowed.
1763    MethodGenericParamUsed,
1764}
1765
1766/// Confirms that a type is not a type parameter referring to one of the
1767/// method's type params.
1768fn confirm_type_is_not_a_method_generic_param(
1769    ty: Ty<'_>,
1770    method_generics: &ty::Generics,
1771) -> Result<(), ReceiverValidityError> {
1772    if let ty::Param(param) = ty.kind() {
1773        if (param.index as usize) >= method_generics.parent_count {
1774            return Err(ReceiverValidityError::MethodGenericParamUsed);
1775        }
1776    }
1777    Ok(())
1778}
1779
1780/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1781/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1782/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1783/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1784/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1785///
1786/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1787/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1788/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1789fn receiver_is_valid<'tcx>(
1790    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1791    span: Span,
1792    receiver_ty: Ty<'tcx>,
1793    self_ty: Ty<'tcx>,
1794    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1795    method_generics: &ty::Generics,
1796) -> Result<(), ReceiverValidityError> {
1797    let infcx = wfcx.infcx;
1798    let tcx = wfcx.tcx();
1799    let cause =
1800        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1801
1802    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1803    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1804        let ocx = ObligationCtxt::new(wfcx.infcx);
1805        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1806        if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1807    }) {
1808        return Ok(());
1809    }
1810
1811    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1812
1813    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1814
1815    // The `arbitrary_self_types` feature allows custom smart pointer
1816    // types to be method receivers, as identified by following the Receiver<Target=T>
1817    // chain.
1818    if arbitrary_self_types_enabled.is_some() {
1819        autoderef = autoderef.use_receiver_trait();
1820    }
1821
1822    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1823    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1824        autoderef = autoderef.include_raw_pointers();
1825    }
1826
1827    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1828    while let Some((potential_self_ty, _)) = autoderef.next() {
1829        debug!(
1830            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1831            potential_self_ty, self_ty
1832        );
1833
1834        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1835
1836        // Check if the self type unifies. If it does, then commit the result
1837        // since it may have region side-effects.
1838        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1839            let ocx = ObligationCtxt::new(wfcx.infcx);
1840            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1841            if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1842        }) {
1843            wfcx.register_obligations(autoderef.into_obligations());
1844            return Ok(());
1845        }
1846
1847        // Without `feature(arbitrary_self_types)`, we require that each step in the
1848        // deref chain implement `LegacyReceiver`.
1849        if arbitrary_self_types_enabled.is_none() {
1850            let legacy_receiver_trait_def_id =
1851                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1852            if !legacy_receiver_is_implemented(
1853                wfcx,
1854                legacy_receiver_trait_def_id,
1855                cause.clone(),
1856                potential_self_ty,
1857            ) {
1858                // We cannot proceed.
1859                break;
1860            }
1861
1862            // Register the bound, in case it has any region side-effects.
1863            wfcx.register_bound(
1864                cause.clone(),
1865                wfcx.param_env,
1866                potential_self_ty,
1867                legacy_receiver_trait_def_id,
1868            );
1869        }
1870    }
1871
1872    debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1873    Err(ReceiverValidityError::DoesNotDeref)
1874}
1875
1876fn legacy_receiver_is_implemented<'tcx>(
1877    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1878    legacy_receiver_trait_def_id: DefId,
1879    cause: ObligationCause<'tcx>,
1880    receiver_ty: Ty<'tcx>,
1881) -> bool {
1882    let tcx = wfcx.tcx();
1883    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1884
1885    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1886
1887    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1888        true
1889    } else {
1890        debug!(
1891            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1892            receiver_ty
1893        );
1894        false
1895    }
1896}
1897
1898pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1899    match tcx.def_kind(def_id) {
1900        DefKind::Enum | DefKind::Struct | DefKind::Union => {
1901            // Ok
1902        }
1903        DefKind::TyAlias => {
1904            assert!(
1905                tcx.type_alias_is_lazy(def_id),
1906                "should not be computing variance of non-free type alias"
1907            );
1908        }
1909        kind => span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1910    }
1911
1912    let ty_predicates = tcx.predicates_of(def_id);
1913    assert_eq!(ty_predicates.parent, None);
1914    let variances = tcx.variances_of(def_id);
1915
1916    let mut constrained_parameters: FxHashSet<_> = variances
1917        .iter()
1918        .enumerate()
1919        .filter(|&(_, &variance)| variance != ty::Bivariant)
1920        .map(|(index, _)| Parameter(index as u32))
1921        .collect();
1922
1923    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1924
1925    // Lazily calculated because it is only needed in case of an error.
1926    let explicitly_bounded_params = LazyCell::new(|| {
1927        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
1928        tcx.hir_node_by_def_id(def_id)
1929            .generics()
1930            .unwrap()
1931            .predicates
1932            .iter()
1933            .filter_map(|predicate| match predicate.kind {
1934                hir::WherePredicateKind::BoundPredicate(predicate) => {
1935                    match icx.lower_ty(predicate.bounded_ty).kind() {
1936                        ty::Param(data) => Some(Parameter(data.index)),
1937                        _ => None,
1938                    }
1939                }
1940                _ => None,
1941            })
1942            .collect::<FxHashSet<_>>()
1943    });
1944
1945    for (index, _) in variances.iter().enumerate() {
1946        let parameter = Parameter(index as u32);
1947
1948        if constrained_parameters.contains(&parameter) {
1949            continue;
1950        }
1951
1952        let node = tcx.hir_node_by_def_id(def_id);
1953        let item = node.expect_item();
1954        let hir_generics = node.generics().unwrap();
1955        let hir_param = &hir_generics.params[index];
1956
1957        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
1958
1959        if ty_param.def_id != hir_param.def_id.into() {
1960            // Valid programs always have lifetimes before types in the generic parameter list.
1961            // ty_generics are normalized to be in this required order, and variances are built
1962            // from ty generics, not from hir generics. but we need hir generics to get
1963            // a span out.
1964            //
1965            // If they aren't in the same order, then the user has written invalid code, and already
1966            // got an error about it (or I'm wrong about this).
1967            tcx.dcx().span_delayed_bug(
1968                hir_param.span,
1969                "hir generics and ty generics in different order",
1970            );
1971            continue;
1972        }
1973
1974        // Look for `ErrorGuaranteed` deeply within this type.
1975        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
1976            .type_of(def_id)
1977            .instantiate_identity()
1978            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
1979        {
1980            continue;
1981        }
1982
1983        match hir_param.name {
1984            hir::ParamName::Error(_) => {
1985                // Don't report a bivariance error for a lifetime that isn't
1986                // even valid to name.
1987            }
1988            _ => {
1989                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
1990                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
1991            }
1992        }
1993    }
1994}
1995
1996/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
1997struct HasErrorDeep<'tcx> {
1998    tcx: TyCtxt<'tcx>,
1999    seen: FxHashSet<DefId>,
2000}
2001impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2002    type Result = ControlFlow<ErrorGuaranteed>;
2003
2004    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2005        match *ty.kind() {
2006            ty::Adt(def, _) => {
2007                if self.seen.insert(def.did()) {
2008                    for field in def.all_fields() {
2009                        self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2010                    }
2011                }
2012            }
2013            ty::Error(guar) => return ControlFlow::Break(guar),
2014            _ => {}
2015        }
2016        ty.super_visit_with(self)
2017    }
2018
2019    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2020        if let Err(guar) = r.error_reported() {
2021            ControlFlow::Break(guar)
2022        } else {
2023            ControlFlow::Continue(())
2024        }
2025    }
2026
2027    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2028        if let Err(guar) = c.error_reported() {
2029            ControlFlow::Break(guar)
2030        } else {
2031            ControlFlow::Continue(())
2032        }
2033    }
2034}
2035
2036fn report_bivariance<'tcx>(
2037    tcx: TyCtxt<'tcx>,
2038    param: &'tcx hir::GenericParam<'tcx>,
2039    has_explicit_bounds: bool,
2040    item: &'tcx hir::Item<'tcx>,
2041) -> ErrorGuaranteed {
2042    let param_name = param.name.ident();
2043
2044    let help = match item.kind {
2045        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2046            if let Some(def_id) = tcx.lang_items().phantom_data() {
2047                errors::UnusedGenericParameterHelp::Adt {
2048                    param_name,
2049                    phantom_data: tcx.def_path_str(def_id),
2050                }
2051            } else {
2052                errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2053            }
2054        }
2055        ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2056        item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2057    };
2058
2059    let mut usage_spans = vec![];
2060    intravisit::walk_item(
2061        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2062        item,
2063    );
2064
2065    if !usage_spans.is_empty() {
2066        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2067        // not actually looking into substitutions, just walking through fields / the "RHS".
2068        // We don't recurse into the hidden types of opaques or anything else fancy.
2069        let item_def_id = item.owner_id.to_def_id();
2070        let is_probably_cyclical =
2071            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2072                .visit_def(item_def_id)
2073                .is_break();
2074        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2075        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2076        // alias, and we should call those parameter usages recursive rather than just saying
2077        // they're unused...
2078        //
2079        // We currently report *all* of the parameter usages, since computing the exact
2080        // subset is very involved, and the fact we're mentioning recursion at all is
2081        // likely to guide the user in the right direction.
2082        if is_probably_cyclical {
2083            return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2084                spans: usage_spans,
2085                param_span: param.span,
2086                param_name,
2087                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2088                help,
2089                note: (),
2090            });
2091        }
2092    }
2093
2094    let const_param_help =
2095        matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2096
2097    let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2098        span: param.span,
2099        param_name,
2100        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2101        usage_spans,
2102        help,
2103        const_param_help,
2104    });
2105    diag.code(E0392);
2106    diag.emit()
2107}
2108
2109/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2110/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2111/// cyclical.
2112///
2113/// Notably, we don't consider substitutions here, so this may have false positives.
2114struct IsProbablyCyclical<'tcx> {
2115    tcx: TyCtxt<'tcx>,
2116    item_def_id: DefId,
2117    seen: FxHashSet<DefId>,
2118}
2119
2120impl<'tcx> IsProbablyCyclical<'tcx> {
2121    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2122        match self.tcx.def_kind(def_id) {
2123            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2124                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2125                    self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2126                })
2127            }
2128            DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2129                self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2130            }
2131            _ => ControlFlow::Continue(()),
2132        }
2133    }
2134}
2135
2136impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2137    type Result = ControlFlow<(), ()>;
2138
2139    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2140        let def_id = match ty.kind() {
2141            ty::Adt(adt_def, _) => Some(adt_def.did()),
2142            ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2143            _ => None,
2144        };
2145        if let Some(def_id) = def_id {
2146            if def_id == self.item_def_id {
2147                return ControlFlow::Break(());
2148            }
2149            if self.seen.insert(def_id) {
2150                self.visit_def(def_id)?;
2151            }
2152        }
2153        ty.super_visit_with(self)
2154    }
2155}
2156
2157/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2158///
2159/// This is used to report places where the user has used parameters in a
2160/// non-variance-constraining way for better bivariance errors.
2161struct CollectUsageSpans<'a> {
2162    spans: &'a mut Vec<Span>,
2163    param_def_id: DefId,
2164}
2165
2166impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2167    type Result = ();
2168
2169    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2170        // Skip the generics. We only care about fields, not where clause/param bounds.
2171    }
2172
2173    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2174        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2175            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2176                && def_id == self.param_def_id
2177            {
2178                self.spans.push(t.span);
2179                return;
2180            } else if let Res::SelfTyAlias { .. } = qpath.res {
2181                self.spans.push(t.span);
2182                return;
2183            }
2184        }
2185        intravisit::walk_ty(self, t);
2186    }
2187}
2188
2189impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2190    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2191    /// aren't true.
2192    #[instrument(level = "debug", skip(self))]
2193    fn check_false_global_bounds(&mut self) {
2194        let tcx = self.ocx.infcx.tcx;
2195        let mut span = tcx.def_span(self.body_def_id);
2196        let empty_env = ty::ParamEnv::empty();
2197
2198        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2199        // Check elaborated bounds.
2200        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2201
2202        for (pred, obligation_span) in implied_obligations {
2203            match pred.kind().skip_binder() {
2204                // We lower empty bounds like `Vec<dyn Copy>:` as
2205                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2206                // regular WF checking
2207                ty::ClauseKind::WellFormed(..)
2208                // Unstable feature goals cannot be proven in an empty environment so skip them
2209                | ty::ClauseKind::UnstableFeature(..) => continue,
2210                _ => {}
2211            }
2212
2213            // Match the existing behavior.
2214            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2215                let pred = self.normalize(span, None, pred);
2216
2217                // only use the span of the predicate clause (#90869)
2218                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2219                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2220                    span = predicates
2221                        .iter()
2222                        // There seems to be no better way to find out which predicate we are in
2223                        .find(|pred| pred.span.contains(obligation_span))
2224                        .map(|pred| pred.span)
2225                        .unwrap_or(obligation_span);
2226                }
2227
2228                let obligation = Obligation::new(
2229                    tcx,
2230                    traits::ObligationCause::new(
2231                        span,
2232                        self.body_def_id,
2233                        ObligationCauseCode::TrivialBound,
2234                    ),
2235                    empty_env,
2236                    pred,
2237                );
2238                self.ocx.register_obligation(obligation);
2239            }
2240        }
2241    }
2242}
2243
2244pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2245    let items = tcx.hir_crate_items(());
2246    let res = items
2247        .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2248        .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2249        .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2250        .and(
2251            items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2252        )
2253        .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2254        .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2255    super::entry::check_for_entry_fn(tcx);
2256
2257    res
2258}
2259
2260fn lint_redundant_lifetimes<'tcx>(
2261    tcx: TyCtxt<'tcx>,
2262    owner_id: LocalDefId,
2263    outlives_env: &OutlivesEnvironment<'tcx>,
2264) {
2265    let def_kind = tcx.def_kind(owner_id);
2266    match def_kind {
2267        DefKind::Struct
2268        | DefKind::Union
2269        | DefKind::Enum
2270        | DefKind::Trait
2271        | DefKind::TraitAlias
2272        | DefKind::Fn
2273        | DefKind::Const
2274        | DefKind::Impl { of_trait: _ } => {
2275            // Proceed
2276        }
2277        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2278            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2279                // Don't check for redundant lifetimes for associated items of trait
2280                // implementations, since the signature is required to be compatible
2281                // with the trait, even if the implementation implies some lifetimes
2282                // are redundant.
2283                return;
2284            }
2285        }
2286        DefKind::Mod
2287        | DefKind::Variant
2288        | DefKind::TyAlias
2289        | DefKind::ForeignTy
2290        | DefKind::TyParam
2291        | DefKind::ConstParam
2292        | DefKind::Static { .. }
2293        | DefKind::Ctor(_, _)
2294        | DefKind::Macro(_)
2295        | DefKind::ExternCrate
2296        | DefKind::Use
2297        | DefKind::ForeignMod
2298        | DefKind::AnonConst
2299        | DefKind::InlineConst
2300        | DefKind::OpaqueTy
2301        | DefKind::Field
2302        | DefKind::LifetimeParam
2303        | DefKind::GlobalAsm
2304        | DefKind::Closure
2305        | DefKind::SyntheticCoroutineBody => return,
2306    }
2307
2308    // The ordering of this lifetime map is a bit subtle.
2309    //
2310    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2311    // where we can prove that `'candidate = 'victim`.
2312    //
2313    // `'static` must come first in this list because we can never replace `'static` with
2314    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2315    // suggest replacing `'a` with `'static`.
2316    let mut lifetimes = vec![tcx.lifetimes.re_static];
2317    lifetimes.extend(
2318        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2319    );
2320    // If we are in a function, add its late-bound lifetimes too.
2321    if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2322        for (idx, var) in
2323            tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2324        {
2325            let ty::BoundVariableKind::Region(kind) = var else { continue };
2326            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2327            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2328        }
2329    }
2330    lifetimes.retain(|candidate| candidate.is_named(tcx));
2331
2332    // Keep track of lifetimes which have already been replaced with other lifetimes.
2333    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2334    // both `'a` and `'b`.
2335    let mut shadowed = FxHashSet::default();
2336
2337    for (idx, &candidate) in lifetimes.iter().enumerate() {
2338        // Don't suggest removing a lifetime twice. We only need to check this
2339        // here and not up in the `victim` loop because equality is transitive,
2340        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2341        // A's victim loop.
2342        if shadowed.contains(&candidate) {
2343            continue;
2344        }
2345
2346        for &victim in &lifetimes[(idx + 1)..] {
2347            // All region parameters should have a `DefId` available as:
2348            // - Late-bound parameters should be of the`BrNamed` variety,
2349            // since we get these signatures straight from `hir_lowering`.
2350            // - Early-bound parameters unconditionally have a `DefId` available.
2351            //
2352            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2353            // can't really suggest to remove them.
2354            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2355                continue;
2356            };
2357
2358            // Do not rename lifetimes not local to this item since they'll overlap
2359            // with the lint running on the parent. We still want to consider parent
2360            // lifetimes which make child lifetimes redundant, otherwise we would
2361            // have truncated the `identity_for_item` args above.
2362            if tcx.parent(def_id) != owner_id.to_def_id() {
2363                continue;
2364            }
2365
2366            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2367            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2368                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2369            {
2370                shadowed.insert(victim);
2371                tcx.emit_node_span_lint(
2372                    rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2373                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2374                    tcx.def_span(def_id),
2375                    RedundantLifetimeArgsLint { candidate, victim },
2376                );
2377            }
2378        }
2379    }
2380}
2381
2382#[derive(LintDiagnostic)]
2383#[diag(hir_analysis_redundant_lifetime_args)]
2384#[note]
2385struct RedundantLifetimeArgsLint<'tcx> {
2386    /// The lifetime we have found to be redundant.
2387    victim: ty::Region<'tcx>,
2388    // The lifetime we can replace the victim with.
2389    candidate: ty::Region<'tcx>,
2390}