rustc_hir_analysis/check/
wfcheck.rs

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