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::SUPERTRAIT_ITEM_SHADOWING_DEFINITION;
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            SUPERTRAIT_ITEM_SHADOWING_DEFINITION,
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        let normalized_bound = wfcx.normalize(span, None, bound);
1156        traits::wf::clause_obligations(
1157            wfcx.infcx,
1158            wfcx.param_env,
1159            wfcx.body_def_id,
1160            normalized_bound,
1161            bound_span,
1162        )
1163    });
1164
1165    wfcx.register_obligations(wf_obligations);
1166}
1167
1168fn check_item_fn(
1169    tcx: TyCtxt<'_>,
1170    def_id: LocalDefId,
1171    decl: &hir::FnDecl<'_>,
1172) -> Result<(), ErrorGuaranteed> {
1173    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1174        let sig = tcx.fn_sig(def_id).instantiate_identity();
1175        check_fn_or_method(wfcx, sig, decl, def_id);
1176        Ok(())
1177    })
1178}
1179
1180#[instrument(level = "debug", skip(tcx))]
1181pub(crate) fn check_static_item<'tcx>(
1182    tcx: TyCtxt<'tcx>,
1183    item_id: LocalDefId,
1184    ty: Ty<'tcx>,
1185    should_check_for_sync: bool,
1186) -> Result<(), ErrorGuaranteed> {
1187    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1188        let span = tcx.ty_span(item_id);
1189        let loc = Some(WellFormedLoc::Ty(item_id));
1190        let item_ty = wfcx.deeply_normalize(span, loc, ty);
1191
1192        let is_foreign_item = tcx.is_foreign_item(item_id);
1193        let is_structurally_foreign_item = || {
1194            let tail = tcx.struct_tail_raw(
1195                item_ty,
1196                &ObligationCause::dummy(),
1197                |ty| wfcx.deeply_normalize(span, loc, ty),
1198                || {},
1199            );
1200
1201            matches!(tail.kind(), ty::Foreign(_))
1202        };
1203        let forbid_unsized = !(is_foreign_item && is_structurally_foreign_item());
1204
1205        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1206        if forbid_unsized {
1207            let span = tcx.def_span(item_id);
1208            wfcx.register_bound(
1209                traits::ObligationCause::new(
1210                    span,
1211                    wfcx.body_def_id,
1212                    ObligationCauseCode::SizedConstOrStatic,
1213                ),
1214                wfcx.param_env,
1215                item_ty,
1216                tcx.require_lang_item(LangItem::Sized, span),
1217            );
1218        }
1219
1220        // Ensure that the end result is `Sync` in a non-thread local `static`.
1221        let should_check_for_sync = should_check_for_sync
1222            && !is_foreign_item
1223            && tcx.static_mutability(item_id.to_def_id()) == Some(hir::Mutability::Not)
1224            && !tcx.is_thread_local_static(item_id.to_def_id());
1225
1226        if should_check_for_sync {
1227            wfcx.register_bound(
1228                traits::ObligationCause::new(
1229                    span,
1230                    wfcx.body_def_id,
1231                    ObligationCauseCode::SharedStatic,
1232                ),
1233                wfcx.param_env,
1234                item_ty,
1235                tcx.require_lang_item(LangItem::Sync, span),
1236            );
1237        }
1238        Ok(())
1239    })
1240}
1241
1242#[instrument(level = "debug", skip(wfcx))]
1243pub(super) fn check_type_const<'tcx>(
1244    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1245    def_id: LocalDefId,
1246    item_ty: Ty<'tcx>,
1247    has_value: bool,
1248) -> Result<(), ErrorGuaranteed> {
1249    let tcx = wfcx.tcx();
1250    let span = tcx.def_span(def_id);
1251
1252    wfcx.register_bound(
1253        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(item_ty)),
1254        wfcx.param_env,
1255        item_ty,
1256        tcx.require_lang_item(LangItem::ConstParamTy, span),
1257    );
1258
1259    if has_value {
1260        let raw_ct = tcx.const_of_item(def_id).instantiate_identity();
1261        let norm_ct = wfcx.deeply_normalize(span, Some(WellFormedLoc::Ty(def_id)), raw_ct);
1262        wfcx.register_wf_obligation(span, Some(WellFormedLoc::Ty(def_id)), norm_ct.into());
1263
1264        wfcx.register_obligation(Obligation::new(
1265            tcx,
1266            ObligationCause::new(span, def_id, ObligationCauseCode::WellFormed(None)),
1267            wfcx.param_env,
1268            ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(norm_ct, item_ty)),
1269        ));
1270    }
1271    Ok(())
1272}
1273
1274#[instrument(level = "debug", skip(tcx, impl_))]
1275fn check_impl<'tcx>(
1276    tcx: TyCtxt<'tcx>,
1277    item: &'tcx hir::Item<'tcx>,
1278    impl_: &hir::Impl<'_>,
1279) -> Result<(), ErrorGuaranteed> {
1280    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1281        match impl_.of_trait {
1282            Some(of_trait) => {
1283                // `#[rustc_reservation_impl]` impls are not real impls and
1284                // therefore don't need to be WF (the trait's `Self: Trait` predicate
1285                // won't hold).
1286                let trait_ref = tcx.impl_trait_ref(item.owner_id).instantiate_identity();
1287                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
1288                // other `Foo` impls are incoherent.
1289                tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1290                let trait_span = of_trait.trait_ref.path.span;
1291                let trait_ref = wfcx.deeply_normalize(
1292                    trait_span,
1293                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1294                    trait_ref,
1295                );
1296                let trait_pred =
1297                    ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1298                let mut obligations = traits::wf::trait_obligations(
1299                    wfcx.infcx,
1300                    wfcx.param_env,
1301                    wfcx.body_def_id,
1302                    trait_pred,
1303                    trait_span,
1304                    item,
1305                );
1306                for obligation in &mut obligations {
1307                    if obligation.cause.span != trait_span {
1308                        // We already have a better span.
1309                        continue;
1310                    }
1311                    if let Some(pred) = obligation.predicate.as_trait_clause()
1312                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1313                    {
1314                        obligation.cause.span = impl_.self_ty.span;
1315                    }
1316                    if let Some(pred) = obligation.predicate.as_projection_clause()
1317                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1318                    {
1319                        obligation.cause.span = impl_.self_ty.span;
1320                    }
1321                }
1322
1323                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1324                if tcx.is_conditionally_const(item.owner_id.def_id) {
1325                    for (bound, _) in
1326                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1327                    {
1328                        let bound = wfcx.normalize(
1329                            item.span,
1330                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1331                            bound,
1332                        );
1333                        wfcx.register_obligation(Obligation::new(
1334                            tcx,
1335                            ObligationCause::new(
1336                                impl_.self_ty.span,
1337                                wfcx.body_def_id,
1338                                ObligationCauseCode::WellFormed(None),
1339                            ),
1340                            wfcx.param_env,
1341                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1342                        ))
1343                    }
1344                }
1345
1346                debug!(?obligations);
1347                wfcx.register_obligations(obligations);
1348            }
1349            None => {
1350                let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1351                let self_ty = wfcx.deeply_normalize(
1352                    item.span,
1353                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1354                    self_ty,
1355                );
1356                wfcx.register_wf_obligation(
1357                    impl_.self_ty.span,
1358                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1359                    self_ty.into(),
1360                );
1361            }
1362        }
1363
1364        check_where_clauses(wfcx, item.owner_id.def_id);
1365        Ok(())
1366    })
1367}
1368
1369/// Checks where-clauses and inline bounds that are declared on `def_id`.
1370#[instrument(level = "debug", skip(wfcx))]
1371pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1372    let infcx = wfcx.infcx;
1373    let tcx = wfcx.tcx();
1374
1375    let predicates = tcx.predicates_of(def_id.to_def_id());
1376    let generics = tcx.generics_of(def_id);
1377
1378    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1379    // For example, this forbids the declaration:
1380    //
1381    //     struct Foo<T = Vec<[u32]>> { .. }
1382    //
1383    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1384    for param in &generics.own_params {
1385        if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1386            // Ignore dependent defaults -- that is, where the default of one type
1387            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1388            // be sure if it will error or not as user might always specify the other.
1389            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1390            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1391            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1392            if !default.has_param() {
1393                wfcx.register_wf_obligation(
1394                    tcx.def_span(param.def_id),
1395                    matches!(param.kind, GenericParamDefKind::Type { .. })
1396                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1397                    default.as_term().unwrap(),
1398                );
1399            } else {
1400                // If we've got a generic const parameter we still want to check its
1401                // type is correct in case both it and the param type are fully concrete.
1402                let GenericArgKind::Const(ct) = default.kind() else {
1403                    continue;
1404                };
1405
1406                let ct_ty = match ct.kind() {
1407                    ty::ConstKind::Infer(_)
1408                    | ty::ConstKind::Placeholder(_)
1409                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1410                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1411                    ty::ConstKind::Value(cv) => cv.ty,
1412                    ty::ConstKind::Unevaluated(uv) => {
1413                        infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1414                    }
1415                    ty::ConstKind::Param(param_ct) => {
1416                        param_ct.find_const_ty_from_env(wfcx.param_env)
1417                    }
1418                };
1419
1420                let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1421                if !ct_ty.has_param() && !param_ty.has_param() {
1422                    let cause = traits::ObligationCause::new(
1423                        tcx.def_span(param.def_id),
1424                        wfcx.body_def_id,
1425                        ObligationCauseCode::WellFormed(None),
1426                    );
1427                    wfcx.register_obligation(Obligation::new(
1428                        tcx,
1429                        cause,
1430                        wfcx.param_env,
1431                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1432                    ));
1433                }
1434            }
1435        }
1436    }
1437
1438    // Check that trait predicates are WF when params are instantiated with their defaults.
1439    // We don't want to overly constrain the predicates that may be written but we want to
1440    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1441    // Therefore we check if a predicate which contains a single type param
1442    // with a concrete default is WF with that default instantiated.
1443    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1444    //
1445    // First we build the defaulted generic parameters.
1446    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1447        if param.index >= generics.parent_count as u32
1448            // If the param has a default, ...
1449            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1450            // ... and it's not a dependent default, ...
1451            && !default.has_param()
1452        {
1453            // ... then instantiate it with the default.
1454            return default;
1455        }
1456        tcx.mk_param_from_def(param)
1457    });
1458
1459    // Now we build the instantiated predicates.
1460    let default_obligations = predicates
1461        .predicates
1462        .iter()
1463        .flat_map(|&(pred, sp)| {
1464            #[derive(Default)]
1465            struct CountParams {
1466                params: FxHashSet<u32>,
1467            }
1468            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1469                type Result = ControlFlow<()>;
1470                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1471                    if let ty::Param(param) = t.kind() {
1472                        self.params.insert(param.index);
1473                    }
1474                    t.super_visit_with(self)
1475                }
1476
1477                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1478                    ControlFlow::Break(())
1479                }
1480
1481                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1482                    if let ty::ConstKind::Param(param) = c.kind() {
1483                        self.params.insert(param.index);
1484                    }
1485                    c.super_visit_with(self)
1486                }
1487            }
1488            let mut param_count = CountParams::default();
1489            let has_region = pred.visit_with(&mut param_count).is_break();
1490            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1491            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1492            // or preds with multiple params.
1493            if instantiated_pred.has_non_region_param()
1494                || param_count.params.len() > 1
1495                || has_region
1496            {
1497                None
1498            } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1499                // Avoid duplication of predicates that contain no parameters, for example.
1500                None
1501            } else {
1502                Some((instantiated_pred, sp))
1503            }
1504        })
1505        .map(|(pred, sp)| {
1506            // Convert each of those into an obligation. So if you have
1507            // something like `struct Foo<T: Copy = String>`, we would
1508            // take that predicate `T: Copy`, instantiated with `String: Copy`
1509            // (actually that happens in the previous `flat_map` call),
1510            // and then try to prove it (in this case, we'll fail).
1511            //
1512            // Note the subtle difference from how we handle `predicates`
1513            // below: there, we are not trying to prove those predicates
1514            // to be *true* but merely *well-formed*.
1515            let pred = wfcx.normalize(sp, None, pred);
1516            let cause = traits::ObligationCause::new(
1517                sp,
1518                wfcx.body_def_id,
1519                ObligationCauseCode::WhereClause(def_id.to_def_id(), sp),
1520            );
1521            Obligation::new(tcx, cause, wfcx.param_env, pred)
1522        });
1523
1524    let predicates = predicates.instantiate_identity(tcx);
1525
1526    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1527    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1528        let p = wfcx.normalize(sp, None, p);
1529        traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1530    });
1531    let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1532    wfcx.register_obligations(obligations);
1533}
1534
1535#[instrument(level = "debug", skip(wfcx, hir_decl))]
1536fn check_fn_or_method<'tcx>(
1537    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1538    sig: ty::PolyFnSig<'tcx>,
1539    hir_decl: &hir::FnDecl<'_>,
1540    def_id: LocalDefId,
1541) {
1542    let tcx = wfcx.tcx();
1543    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1544
1545    // Normalize the input and output types one at a time, using a different
1546    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1547    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1548    // for each type, preventing the HIR wf check from generating
1549    // a nice error message.
1550    let arg_span =
1551        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1552
1553    sig.inputs_and_output =
1554        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1555            wfcx.deeply_normalize(
1556                arg_span(idx),
1557                Some(WellFormedLoc::Param {
1558                    function: def_id,
1559                    // Note that the `param_idx` of the output type is
1560                    // one greater than the index of the last input type.
1561                    param_idx: idx,
1562                }),
1563                ty,
1564            )
1565        }));
1566
1567    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1568        wfcx.register_wf_obligation(
1569            arg_span(idx),
1570            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1571            ty.into(),
1572        );
1573    }
1574
1575    check_where_clauses(wfcx, def_id);
1576
1577    if sig.abi == ExternAbi::RustCall {
1578        let span = tcx.def_span(def_id);
1579        let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1580        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1581        // Check that the argument is a tuple and is sized
1582        if let Some(ty) = inputs.next() {
1583            wfcx.register_bound(
1584                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1585                wfcx.param_env,
1586                *ty,
1587                tcx.require_lang_item(hir::LangItem::Tuple, span),
1588            );
1589            wfcx.register_bound(
1590                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1591                wfcx.param_env,
1592                *ty,
1593                tcx.require_lang_item(hir::LangItem::Sized, span),
1594            );
1595        } else {
1596            tcx.dcx().span_err(
1597                hir_decl.inputs.last().map_or(span, |input| input.span),
1598                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1599            );
1600        }
1601        // No more inputs other than the `self` type and the tuple type
1602        if inputs.next().is_some() {
1603            tcx.dcx().span_err(
1604                hir_decl.inputs.last().map_or(span, |input| input.span),
1605                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1606            );
1607        }
1608    }
1609
1610    // If the function has a body, additionally require that the return type is sized.
1611    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1612        let span = match hir_decl.output {
1613            hir::FnRetTy::Return(ty) => ty.span,
1614            hir::FnRetTy::DefaultReturn(_) => body.value.span,
1615        };
1616
1617        wfcx.register_bound(
1618            ObligationCause::new(span, def_id, ObligationCauseCode::SizedReturnType),
1619            wfcx.param_env,
1620            sig.output(),
1621            tcx.require_lang_item(LangItem::Sized, span),
1622        );
1623    }
1624}
1625
1626/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1627#[derive(Clone, Copy, PartialEq)]
1628enum ArbitrarySelfTypesLevel {
1629    Basic,        // just arbitrary_self_types
1630    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1631}
1632
1633#[instrument(level = "debug", skip(wfcx))]
1634fn check_method_receiver<'tcx>(
1635    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1636    fn_sig: &hir::FnSig<'_>,
1637    method: ty::AssocItem,
1638    self_ty: Ty<'tcx>,
1639) -> Result<(), ErrorGuaranteed> {
1640    let tcx = wfcx.tcx();
1641
1642    if !method.is_method() {
1643        return Ok(());
1644    }
1645
1646    let span = fn_sig.decl.inputs[0].span;
1647    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1648
1649    let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1650    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1651    let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1652
1653    debug!("check_method_receiver: sig={:?}", sig);
1654
1655    let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1656
1657    let receiver_ty = sig.inputs()[0];
1658    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1659
1660    // If the receiver already has errors reported, consider it valid to avoid
1661    // unnecessary errors (#58712).
1662    receiver_ty.error_reported()?;
1663
1664    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1665        Some(ArbitrarySelfTypesLevel::WithPointers)
1666    } else if tcx.features().arbitrary_self_types() {
1667        Some(ArbitrarySelfTypesLevel::Basic)
1668    } else {
1669        None
1670    };
1671    let generics = tcx.generics_of(method.def_id);
1672
1673    let receiver_validity =
1674        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1675    if let Err(receiver_validity_err) = receiver_validity {
1676        return Err(match arbitrary_self_types_level {
1677            // Wherever possible, emit a message advising folks that the features
1678            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1679            // have helped.
1680            None if receiver_is_valid(
1681                wfcx,
1682                span,
1683                receiver_ty,
1684                self_ty,
1685                Some(ArbitrarySelfTypesLevel::Basic),
1686                generics,
1687            )
1688            .is_ok() =>
1689            {
1690                // Report error; would have worked with `arbitrary_self_types`.
1691                feature_err(
1692                    &tcx.sess,
1693                    sym::arbitrary_self_types,
1694                    span,
1695                    format!(
1696                        "`{receiver_ty}` cannot be used as the type of `self` without \
1697                            the `arbitrary_self_types` feature",
1698                    ),
1699                )
1700                .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1701                .emit()
1702            }
1703            None | Some(ArbitrarySelfTypesLevel::Basic)
1704                if receiver_is_valid(
1705                    wfcx,
1706                    span,
1707                    receiver_ty,
1708                    self_ty,
1709                    Some(ArbitrarySelfTypesLevel::WithPointers),
1710                    generics,
1711                )
1712                .is_ok() =>
1713            {
1714                // Report error; would have worked with `arbitrary_self_types_pointers`.
1715                feature_err(
1716                    &tcx.sess,
1717                    sym::arbitrary_self_types_pointers,
1718                    span,
1719                    format!(
1720                        "`{receiver_ty}` cannot be used as the type of `self` without \
1721                            the `arbitrary_self_types_pointers` feature",
1722                    ),
1723                )
1724                .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1725                .emit()
1726            }
1727            _ =>
1728            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1729            {
1730                match receiver_validity_err {
1731                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1732                        let hint = match receiver_ty
1733                            .builtin_deref(false)
1734                            .unwrap_or(receiver_ty)
1735                            .ty_adt_def()
1736                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1737                        {
1738                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1739                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1740                            _ => None,
1741                        };
1742
1743                        tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1744                    }
1745                    ReceiverValidityError::DoesNotDeref => {
1746                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1747                            span,
1748                            receiver_ty,
1749                        })
1750                    }
1751                    ReceiverValidityError::MethodGenericParamUsed => {
1752                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1753                    }
1754                }
1755            }
1756        });
1757    }
1758    Ok(())
1759}
1760
1761/// Error cases which may be returned from `receiver_is_valid`. These error
1762/// cases are generated in this function as they may be unearthed as we explore
1763/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1764enum ReceiverValidityError {
1765    /// The self type does not get to the receiver type by following the
1766    /// autoderef chain.
1767    DoesNotDeref,
1768    /// A type was found which is a method type parameter, and that's not allowed.
1769    MethodGenericParamUsed,
1770}
1771
1772/// Confirms that a type is not a type parameter referring to one of the
1773/// method's type params.
1774fn confirm_type_is_not_a_method_generic_param(
1775    ty: Ty<'_>,
1776    method_generics: &ty::Generics,
1777) -> Result<(), ReceiverValidityError> {
1778    if let ty::Param(param) = ty.kind() {
1779        if (param.index as usize) >= method_generics.parent_count {
1780            return Err(ReceiverValidityError::MethodGenericParamUsed);
1781        }
1782    }
1783    Ok(())
1784}
1785
1786/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1787/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1788/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1789/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1790/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1791///
1792/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1793/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1794/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1795fn receiver_is_valid<'tcx>(
1796    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1797    span: Span,
1798    receiver_ty: Ty<'tcx>,
1799    self_ty: Ty<'tcx>,
1800    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1801    method_generics: &ty::Generics,
1802) -> Result<(), ReceiverValidityError> {
1803    let infcx = wfcx.infcx;
1804    let tcx = wfcx.tcx();
1805    let cause =
1806        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1807
1808    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1809    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1810        let ocx = ObligationCtxt::new(wfcx.infcx);
1811        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1812        if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1813            Ok(())
1814        } else {
1815            Err(NoSolution)
1816        }
1817    }) {
1818        return Ok(());
1819    }
1820
1821    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1822
1823    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1824
1825    // The `arbitrary_self_types` feature allows custom smart pointer
1826    // types to be method receivers, as identified by following the Receiver<Target=T>
1827    // chain.
1828    if arbitrary_self_types_enabled.is_some() {
1829        autoderef = autoderef.use_receiver_trait();
1830    }
1831
1832    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1833    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1834        autoderef = autoderef.include_raw_pointers();
1835    }
1836
1837    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1838    while let Some((potential_self_ty, _)) = autoderef.next() {
1839        debug!(
1840            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1841            potential_self_ty, self_ty
1842        );
1843
1844        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1845
1846        // Check if the self type unifies. If it does, then commit the result
1847        // since it may have region side-effects.
1848        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1849            let ocx = ObligationCtxt::new(wfcx.infcx);
1850            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1851            if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
1852                Ok(())
1853            } else {
1854                Err(NoSolution)
1855            }
1856        }) {
1857            wfcx.register_obligations(autoderef.into_obligations());
1858            return Ok(());
1859        }
1860
1861        // Without `feature(arbitrary_self_types)`, we require that each step in the
1862        // deref chain implement `LegacyReceiver`.
1863        if arbitrary_self_types_enabled.is_none() {
1864            let legacy_receiver_trait_def_id =
1865                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1866            if !legacy_receiver_is_implemented(
1867                wfcx,
1868                legacy_receiver_trait_def_id,
1869                cause.clone(),
1870                potential_self_ty,
1871            ) {
1872                // We cannot proceed.
1873                break;
1874            }
1875
1876            // Register the bound, in case it has any region side-effects.
1877            wfcx.register_bound(
1878                cause.clone(),
1879                wfcx.param_env,
1880                potential_self_ty,
1881                legacy_receiver_trait_def_id,
1882            );
1883        }
1884    }
1885
1886    debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1887    Err(ReceiverValidityError::DoesNotDeref)
1888}
1889
1890fn legacy_receiver_is_implemented<'tcx>(
1891    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1892    legacy_receiver_trait_def_id: DefId,
1893    cause: ObligationCause<'tcx>,
1894    receiver_ty: Ty<'tcx>,
1895) -> bool {
1896    let tcx = wfcx.tcx();
1897    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1898
1899    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1900
1901    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1902        true
1903    } else {
1904        debug!(
1905            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1906            receiver_ty
1907        );
1908        false
1909    }
1910}
1911
1912pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1913    match tcx.def_kind(def_id) {
1914        DefKind::Enum | DefKind::Struct | DefKind::Union => {
1915            // Ok
1916        }
1917        DefKind::TyAlias => {
1918            assert!(
1919                tcx.type_alias_is_lazy(def_id),
1920                "should not be computing variance of non-free type alias"
1921            );
1922        }
1923        kind => span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1924    }
1925
1926    let ty_predicates = tcx.predicates_of(def_id);
1927    assert_eq!(ty_predicates.parent, None);
1928    let variances = tcx.variances_of(def_id);
1929
1930    let mut constrained_parameters: FxHashSet<_> = variances
1931        .iter()
1932        .enumerate()
1933        .filter(|&(_, &variance)| variance != ty::Bivariant)
1934        .map(|(index, _)| Parameter(index as u32))
1935        .collect();
1936
1937    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1938
1939    // Lazily calculated because it is only needed in case of an error.
1940    let explicitly_bounded_params = LazyCell::new(|| {
1941        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
1942        tcx.hir_node_by_def_id(def_id)
1943            .generics()
1944            .unwrap()
1945            .predicates
1946            .iter()
1947            .filter_map(|predicate| match predicate.kind {
1948                hir::WherePredicateKind::BoundPredicate(predicate) => {
1949                    match icx.lower_ty(predicate.bounded_ty).kind() {
1950                        ty::Param(data) => Some(Parameter(data.index)),
1951                        _ => None,
1952                    }
1953                }
1954                _ => None,
1955            })
1956            .collect::<FxHashSet<_>>()
1957    });
1958
1959    for (index, _) in variances.iter().enumerate() {
1960        let parameter = Parameter(index as u32);
1961
1962        if constrained_parameters.contains(&parameter) {
1963            continue;
1964        }
1965
1966        let node = tcx.hir_node_by_def_id(def_id);
1967        let item = node.expect_item();
1968        let hir_generics = node.generics().unwrap();
1969        let hir_param = &hir_generics.params[index];
1970
1971        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
1972
1973        if ty_param.def_id != hir_param.def_id.into() {
1974            // Valid programs always have lifetimes before types in the generic parameter list.
1975            // ty_generics are normalized to be in this required order, and variances are built
1976            // from ty generics, not from hir generics. but we need hir generics to get
1977            // a span out.
1978            //
1979            // If they aren't in the same order, then the user has written invalid code, and already
1980            // got an error about it (or I'm wrong about this).
1981            tcx.dcx().span_delayed_bug(
1982                hir_param.span,
1983                "hir generics and ty generics in different order",
1984            );
1985            continue;
1986        }
1987
1988        // Look for `ErrorGuaranteed` deeply within this type.
1989        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
1990            .type_of(def_id)
1991            .instantiate_identity()
1992            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
1993        {
1994            continue;
1995        }
1996
1997        match hir_param.name {
1998            hir::ParamName::Error(_) => {
1999                // Don't report a bivariance error for a lifetime that isn't
2000                // even valid to name.
2001            }
2002            _ => {
2003                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2004                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2005            }
2006        }
2007    }
2008}
2009
2010/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2011struct HasErrorDeep<'tcx> {
2012    tcx: TyCtxt<'tcx>,
2013    seen: FxHashSet<DefId>,
2014}
2015impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2016    type Result = ControlFlow<ErrorGuaranteed>;
2017
2018    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2019        match *ty.kind() {
2020            ty::Adt(def, _) => {
2021                if self.seen.insert(def.did()) {
2022                    for field in def.all_fields() {
2023                        self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2024                    }
2025                }
2026            }
2027            ty::Error(guar) => return ControlFlow::Break(guar),
2028            _ => {}
2029        }
2030        ty.super_visit_with(self)
2031    }
2032
2033    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2034        if let Err(guar) = r.error_reported() {
2035            ControlFlow::Break(guar)
2036        } else {
2037            ControlFlow::Continue(())
2038        }
2039    }
2040
2041    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2042        if let Err(guar) = c.error_reported() {
2043            ControlFlow::Break(guar)
2044        } else {
2045            ControlFlow::Continue(())
2046        }
2047    }
2048}
2049
2050fn report_bivariance<'tcx>(
2051    tcx: TyCtxt<'tcx>,
2052    param: &'tcx hir::GenericParam<'tcx>,
2053    has_explicit_bounds: bool,
2054    item: &'tcx hir::Item<'tcx>,
2055) -> ErrorGuaranteed {
2056    let param_name = param.name.ident();
2057
2058    let help = match item.kind {
2059        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2060            if let Some(def_id) = tcx.lang_items().phantom_data() {
2061                errors::UnusedGenericParameterHelp::Adt {
2062                    param_name,
2063                    phantom_data: tcx.def_path_str(def_id),
2064                }
2065            } else {
2066                errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2067            }
2068        }
2069        ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2070        item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2071    };
2072
2073    let mut usage_spans = vec![];
2074    intravisit::walk_item(
2075        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2076        item,
2077    );
2078
2079    if !usage_spans.is_empty() {
2080        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2081        // not actually looking into substitutions, just walking through fields / the "RHS".
2082        // We don't recurse into the hidden types of opaques or anything else fancy.
2083        let item_def_id = item.owner_id.to_def_id();
2084        let is_probably_cyclical =
2085            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2086                .visit_def(item_def_id)
2087                .is_break();
2088        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2089        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2090        // alias, and we should call those parameter usages recursive rather than just saying
2091        // they're unused...
2092        //
2093        // We currently report *all* of the parameter usages, since computing the exact
2094        // subset is very involved, and the fact we're mentioning recursion at all is
2095        // likely to guide the user in the right direction.
2096        if is_probably_cyclical {
2097            return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2098                spans: usage_spans,
2099                param_span: param.span,
2100                param_name,
2101                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2102                help,
2103                note: (),
2104            });
2105        }
2106    }
2107
2108    let const_param_help =
2109        matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2110
2111    let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2112        span: param.span,
2113        param_name,
2114        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2115        usage_spans,
2116        help,
2117        const_param_help,
2118    });
2119    diag.code(E0392);
2120    diag.emit()
2121}
2122
2123/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2124/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2125/// cyclical.
2126///
2127/// Notably, we don't consider substitutions here, so this may have false positives.
2128struct IsProbablyCyclical<'tcx> {
2129    tcx: TyCtxt<'tcx>,
2130    item_def_id: DefId,
2131    seen: FxHashSet<DefId>,
2132}
2133
2134impl<'tcx> IsProbablyCyclical<'tcx> {
2135    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2136        match self.tcx.def_kind(def_id) {
2137            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2138                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2139                    self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2140                })
2141            }
2142            DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2143                self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2144            }
2145            _ => ControlFlow::Continue(()),
2146        }
2147    }
2148}
2149
2150impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2151    type Result = ControlFlow<(), ()>;
2152
2153    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2154        let def_id = match ty.kind() {
2155            ty::Adt(adt_def, _) => Some(adt_def.did()),
2156            ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2157            _ => None,
2158        };
2159        if let Some(def_id) = def_id {
2160            if def_id == self.item_def_id {
2161                return ControlFlow::Break(());
2162            }
2163            if self.seen.insert(def_id) {
2164                self.visit_def(def_id)?;
2165            }
2166        }
2167        ty.super_visit_with(self)
2168    }
2169}
2170
2171/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2172///
2173/// This is used to report places where the user has used parameters in a
2174/// non-variance-constraining way for better bivariance errors.
2175struct CollectUsageSpans<'a> {
2176    spans: &'a mut Vec<Span>,
2177    param_def_id: DefId,
2178}
2179
2180impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2181    type Result = ();
2182
2183    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2184        // Skip the generics. We only care about fields, not where clause/param bounds.
2185    }
2186
2187    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2188        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2189            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2190                && def_id == self.param_def_id
2191            {
2192                self.spans.push(t.span);
2193                return;
2194            } else if let Res::SelfTyAlias { .. } = qpath.res {
2195                self.spans.push(t.span);
2196                return;
2197            }
2198        }
2199        intravisit::walk_ty(self, t);
2200    }
2201}
2202
2203impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2204    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2205    /// aren't true.
2206    #[instrument(level = "debug", skip(self))]
2207    fn check_false_global_bounds(&mut self) {
2208        let tcx = self.ocx.infcx.tcx;
2209        let mut span = tcx.def_span(self.body_def_id);
2210        let empty_env = ty::ParamEnv::empty();
2211
2212        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2213        // Check elaborated bounds.
2214        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2215
2216        for (pred, obligation_span) in implied_obligations {
2217            match pred.kind().skip_binder() {
2218                // We lower empty bounds like `Vec<dyn Copy>:` as
2219                // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2220                // regular WF checking
2221                ty::ClauseKind::WellFormed(..)
2222                // Unstable feature goals cannot be proven in an empty environment so skip them
2223                | ty::ClauseKind::UnstableFeature(..) => continue,
2224                _ => {}
2225            }
2226
2227            // Match the existing behavior.
2228            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2229                let pred = self.normalize(span, None, pred);
2230
2231                // only use the span of the predicate clause (#90869)
2232                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2233                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2234                    span = predicates
2235                        .iter()
2236                        // There seems to be no better way to find out which predicate we are in
2237                        .find(|pred| pred.span.contains(obligation_span))
2238                        .map(|pred| pred.span)
2239                        .unwrap_or(obligation_span);
2240                }
2241
2242                let obligation = Obligation::new(
2243                    tcx,
2244                    traits::ObligationCause::new(
2245                        span,
2246                        self.body_def_id,
2247                        ObligationCauseCode::TrivialBound,
2248                    ),
2249                    empty_env,
2250                    pred,
2251                );
2252                self.ocx.register_obligation(obligation);
2253            }
2254        }
2255    }
2256}
2257
2258pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2259    let items = tcx.hir_crate_items(());
2260    let res = items
2261        .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2262        .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2263        .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2264        .and(
2265            items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2266        )
2267        .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2268        .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2269    super::entry::check_for_entry_fn(tcx);
2270
2271    res
2272}
2273
2274fn lint_redundant_lifetimes<'tcx>(
2275    tcx: TyCtxt<'tcx>,
2276    owner_id: LocalDefId,
2277    outlives_env: &OutlivesEnvironment<'tcx>,
2278) {
2279    let def_kind = tcx.def_kind(owner_id);
2280    match def_kind {
2281        DefKind::Struct
2282        | DefKind::Union
2283        | DefKind::Enum
2284        | DefKind::Trait
2285        | DefKind::TraitAlias
2286        | DefKind::Fn
2287        | DefKind::Const
2288        | DefKind::Impl { of_trait: _ } => {
2289            // Proceed
2290        }
2291        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2292            if tcx.trait_impl_of_assoc(owner_id.to_def_id()).is_some() {
2293                // Don't check for redundant lifetimes for associated items of trait
2294                // implementations, since the signature is required to be compatible
2295                // with the trait, even if the implementation implies some lifetimes
2296                // are redundant.
2297                return;
2298            }
2299        }
2300        DefKind::Mod
2301        | DefKind::Variant
2302        | DefKind::TyAlias
2303        | DefKind::ForeignTy
2304        | DefKind::TyParam
2305        | DefKind::ConstParam
2306        | DefKind::Static { .. }
2307        | DefKind::Ctor(_, _)
2308        | DefKind::Macro(_)
2309        | DefKind::ExternCrate
2310        | DefKind::Use
2311        | DefKind::ForeignMod
2312        | DefKind::AnonConst
2313        | DefKind::InlineConst
2314        | DefKind::OpaqueTy
2315        | DefKind::Field
2316        | DefKind::LifetimeParam
2317        | DefKind::GlobalAsm
2318        | DefKind::Closure
2319        | DefKind::SyntheticCoroutineBody => return,
2320    }
2321
2322    // The ordering of this lifetime map is a bit subtle.
2323    //
2324    // Specifically, we want to find a "candidate" lifetime that precedes a "victim" lifetime,
2325    // where we can prove that `'candidate = 'victim`.
2326    //
2327    // `'static` must come first in this list because we can never replace `'static` with
2328    // something else, but if we find some lifetime `'a` where `'a = 'static`, we want to
2329    // suggest replacing `'a` with `'static`.
2330    let mut lifetimes = vec![tcx.lifetimes.re_static];
2331    lifetimes.extend(
2332        ty::GenericArgs::identity_for_item(tcx, owner_id).iter().filter_map(|arg| arg.as_region()),
2333    );
2334    // If we are in a function, add its late-bound lifetimes too.
2335    if matches!(def_kind, DefKind::Fn | DefKind::AssocFn) {
2336        for (idx, var) in
2337            tcx.fn_sig(owner_id).instantiate_identity().bound_vars().iter().enumerate()
2338        {
2339            let ty::BoundVariableKind::Region(kind) = var else { continue };
2340            let kind = ty::LateParamRegionKind::from_bound(ty::BoundVar::from_usize(idx), kind);
2341            lifetimes.push(ty::Region::new_late_param(tcx, owner_id.to_def_id(), kind));
2342        }
2343    }
2344    lifetimes.retain(|candidate| candidate.is_named(tcx));
2345
2346    // Keep track of lifetimes which have already been replaced with other lifetimes.
2347    // This makes sure that if `'a = 'b = 'c`, we don't say `'c` should be replaced by
2348    // both `'a` and `'b`.
2349    let mut shadowed = FxHashSet::default();
2350
2351    for (idx, &candidate) in lifetimes.iter().enumerate() {
2352        // Don't suggest removing a lifetime twice. We only need to check this
2353        // here and not up in the `victim` loop because equality is transitive,
2354        // so if A = C and B = C, then A must = B, so it'll be shadowed too in
2355        // A's victim loop.
2356        if shadowed.contains(&candidate) {
2357            continue;
2358        }
2359
2360        for &victim in &lifetimes[(idx + 1)..] {
2361            // All region parameters should have a `DefId` available as:
2362            // - Late-bound parameters should be of the`BrNamed` variety,
2363            // since we get these signatures straight from `hir_lowering`.
2364            // - Early-bound parameters unconditionally have a `DefId` available.
2365            //
2366            // Any other regions (ReError/ReStatic/etc.) shouldn't matter, since we
2367            // can't really suggest to remove them.
2368            let Some(def_id) = victim.opt_param_def_id(tcx, owner_id.to_def_id()) else {
2369                continue;
2370            };
2371
2372            // Do not rename lifetimes not local to this item since they'll overlap
2373            // with the lint running on the parent. We still want to consider parent
2374            // lifetimes which make child lifetimes redundant, otherwise we would
2375            // have truncated the `identity_for_item` args above.
2376            if tcx.parent(def_id) != owner_id.to_def_id() {
2377                continue;
2378            }
2379
2380            // If `candidate <: victim` and `victim <: candidate`, then they're equal.
2381            if outlives_env.free_region_map().sub_free_regions(tcx, candidate, victim)
2382                && outlives_env.free_region_map().sub_free_regions(tcx, victim, candidate)
2383            {
2384                shadowed.insert(victim);
2385                tcx.emit_node_span_lint(
2386                    rustc_lint_defs::builtin::REDUNDANT_LIFETIMES,
2387                    tcx.local_def_id_to_hir_id(def_id.expect_local()),
2388                    tcx.def_span(def_id),
2389                    RedundantLifetimeArgsLint { candidate, victim },
2390                );
2391            }
2392        }
2393    }
2394}
2395
2396#[derive(LintDiagnostic)]
2397#[diag(hir_analysis_redundant_lifetime_args)]
2398#[note]
2399struct RedundantLifetimeArgsLint<'tcx> {
2400    /// The lifetime we have found to be redundant.
2401    victim: ty::Region<'tcx>,
2402    // The lifetime we can replace the victim with.
2403    candidate: ty::Region<'tcx>,
2404}