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