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(impl_) => {
248            let header = tcx.impl_trait_header(def_id);
249            let is_auto = header
250                .is_some_and(|header| tcx.trait_is_auto(header.trait_ref.skip_binder().def_id));
251
252            crate::impl_wf_check::check_impl_wf(tcx, def_id)?;
253            let mut res = Ok(());
254            if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
255                let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
256                res = Err(tcx
257                    .dcx()
258                    .struct_span_err(sp, "impls of auto traits cannot be default")
259                    .with_span_labels(impl_.defaultness_span, "default because of this")
260                    .with_span_label(sp, "auto trait")
261                    .emit());
262            }
263            // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
264            match header.map(|h| h.polarity) {
265                // `None` means this is an inherent impl
266                Some(ty::ImplPolarity::Positive) | None => {
267                    res = res.and(check_impl(tcx, item, impl_.self_ty, &impl_.of_trait));
268                }
269                Some(ty::ImplPolarity::Negative) => {
270                    let ast::ImplPolarity::Negative(span) = impl_.polarity else {
271                        bug!("impl_polarity query disagrees with impl's polarity in HIR");
272                    };
273                    // FIXME(#27579): what amount of WF checking do we need for neg impls?
274                    if let hir::Defaultness::Default { .. } = impl_.defaultness {
275                        let mut spans = vec![span];
276                        spans.extend(impl_.defaultness_span);
277                        res = Err(struct_span_code_err!(
278                            tcx.dcx(),
279                            spans,
280                            E0750,
281                            "negative impls cannot be default impls"
282                        )
283                        .emit());
284                    }
285                }
286                Some(ty::ImplPolarity::Reservation) => {
287                    // FIXME: what amount of WF checking do we need for reservation impls?
288                }
289            }
290            res
291        }
292        hir::ItemKind::Fn { sig, .. } => check_item_fn(tcx, def_id, sig.decl),
293        hir::ItemKind::Const(_, _, ty, _) => check_const_item(tcx, def_id, ty.span),
294        hir::ItemKind::Struct(..) => check_type_defn(tcx, item, false),
295        hir::ItemKind::Union(..) => check_type_defn(tcx, item, true),
296        hir::ItemKind::Enum(..) => check_type_defn(tcx, item, true),
297        hir::ItemKind::Trait(..) => check_trait(tcx, item),
298        hir::ItemKind::TraitAlias(..) => check_trait(tcx, item),
299        _ => Ok(()),
300    }
301}
302
303pub(super) fn check_foreign_item<'tcx>(
304    tcx: TyCtxt<'tcx>,
305    item: &'tcx hir::ForeignItem<'tcx>,
306) -> Result<(), ErrorGuaranteed> {
307    let def_id = item.owner_id.def_id;
308
309    debug!(
310        ?item.owner_id,
311        item.name = ? tcx.def_path_str(def_id)
312    );
313
314    match item.kind {
315        hir::ForeignItemKind::Fn(sig, ..) => check_item_fn(tcx, def_id, sig.decl),
316        hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => Ok(()),
317    }
318}
319
320pub(crate) fn check_trait_item<'tcx>(
321    tcx: TyCtxt<'tcx>,
322    def_id: LocalDefId,
323) -> Result<(), ErrorGuaranteed> {
324    // Check that an item definition in a subtrait is shadowing a supertrait item.
325    lint_item_shadowing_supertrait_item(tcx, def_id);
326
327    let mut res = Ok(());
328
329    if matches!(tcx.def_kind(def_id), DefKind::AssocFn) {
330        for &assoc_ty_def_id in tcx.associated_types_for_impl_traits_in_associated_fn(def_id) {
331            res = res.and(check_associated_item(tcx, assoc_ty_def_id.expect_local()));
332        }
333    }
334    res
335}
336
337/// Require that the user writes where clauses on GATs for the implicit
338/// outlives bounds involving trait parameters in trait functions and
339/// lifetimes passed as GAT args. See `self-outlives-lint` test.
340///
341/// We use the following trait as an example throughout this function:
342/// ```rust,ignore (this code fails due to this lint)
343/// trait IntoIter {
344///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
345///     type Item<'a>;
346///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
347/// }
348/// ```
349fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
350    // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
351    let mut required_bounds_by_item = FxIndexMap::default();
352    let associated_items = tcx.associated_items(trait_def_id);
353
354    // Loop over all GATs together, because if this lint suggests adding a where-clause bound
355    // to one GAT, it might then require us to an additional bound on another GAT.
356    // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
357    // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
358    // those GATs.
359    loop {
360        let mut should_continue = false;
361        for gat_item in associated_items.in_definition_order() {
362            let gat_def_id = gat_item.def_id.expect_local();
363            let gat_item = tcx.associated_item(gat_def_id);
364            // If this item is not an assoc ty, or has no args, then it's not a GAT
365            if !gat_item.is_type() {
366                continue;
367            }
368            let gat_generics = tcx.generics_of(gat_def_id);
369            // FIXME(jackh726): we can also warn in the more general case
370            if gat_generics.is_own_empty() {
371                continue;
372            }
373
374            // Gather the bounds with which all other items inside of this trait constrain the GAT.
375            // This is calculated by taking the intersection of the bounds that each item
376            // constrains the GAT with individually.
377            let mut new_required_bounds: Option<FxIndexSet<ty::Clause<'_>>> = None;
378            for item in associated_items.in_definition_order() {
379                let item_def_id = item.def_id.expect_local();
380                // Skip our own GAT, since it does not constrain itself at all.
381                if item_def_id == gat_def_id {
382                    continue;
383                }
384
385                let param_env = tcx.param_env(item_def_id);
386
387                let item_required_bounds = match tcx.associated_item(item_def_id).kind {
388                    // In our example, this corresponds to `into_iter` method
389                    ty::AssocKind::Fn { .. } => {
390                        // For methods, we check the function signature's return type for any GATs
391                        // to constrain. In the `into_iter` case, we see that the return type
392                        // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
393                        let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
394                            item_def_id.to_def_id(),
395                            tcx.fn_sig(item_def_id).instantiate_identity(),
396                        );
397                        gather_gat_bounds(
398                            tcx,
399                            param_env,
400                            item_def_id,
401                            sig.inputs_and_output,
402                            // We also assume that all of the function signature's parameter types
403                            // are well formed.
404                            &sig.inputs().iter().copied().collect(),
405                            gat_def_id,
406                            gat_generics,
407                        )
408                    }
409                    // In our example, this corresponds to the `Iter` and `Item` associated types
410                    ty::AssocKind::Type { .. } => {
411                        // If our associated item is a GAT with missing bounds, add them to
412                        // the param-env here. This allows this GAT to propagate missing bounds
413                        // to other GATs.
414                        let param_env = augment_param_env(
415                            tcx,
416                            param_env,
417                            required_bounds_by_item.get(&item_def_id),
418                        );
419                        gather_gat_bounds(
420                            tcx,
421                            param_env,
422                            item_def_id,
423                            tcx.explicit_item_bounds(item_def_id)
424                                .iter_identity_copied()
425                                .collect::<Vec<_>>(),
426                            &FxIndexSet::default(),
427                            gat_def_id,
428                            gat_generics,
429                        )
430                    }
431                    ty::AssocKind::Const { .. } => None,
432                };
433
434                if let Some(item_required_bounds) = item_required_bounds {
435                    // Take the intersection of the required bounds for this GAT, and
436                    // the item_required_bounds which are the ones implied by just
437                    // this item alone.
438                    // This is why we use an Option<_>, since we need to distinguish
439                    // the empty set of bounds from the _uninitialized_ set of bounds.
440                    if let Some(new_required_bounds) = &mut new_required_bounds {
441                        new_required_bounds.retain(|b| item_required_bounds.contains(b));
442                    } else {
443                        new_required_bounds = Some(item_required_bounds);
444                    }
445                }
446            }
447
448            if let Some(new_required_bounds) = new_required_bounds {
449                let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
450                if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
451                    // Iterate until our required_bounds no longer change
452                    // Since they changed here, we should continue the loop
453                    should_continue = true;
454                }
455            }
456        }
457        // We know that this loop will eventually halt, since we only set `should_continue` if the
458        // `required_bounds` for this item grows. Since we are not creating any new region or type
459        // variables, the set of all region and type bounds that we could ever insert are limited
460        // by the number of unique types and regions we observe in a given item.
461        if !should_continue {
462            break;
463        }
464    }
465
466    for (gat_def_id, required_bounds) in required_bounds_by_item {
467        // Don't suggest adding `Self: 'a` to a GAT that can't be named
468        if tcx.is_impl_trait_in_trait(gat_def_id.to_def_id()) {
469            continue;
470        }
471
472        let gat_item_hir = tcx.hir_expect_trait_item(gat_def_id);
473        debug!(?required_bounds);
474        let param_env = tcx.param_env(gat_def_id);
475
476        let unsatisfied_bounds: Vec<_> = required_bounds
477            .into_iter()
478            .filter(|clause| match clause.kind().skip_binder() {
479                ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
480                    !region_known_to_outlive(
481                        tcx,
482                        gat_def_id,
483                        param_env,
484                        &FxIndexSet::default(),
485                        a,
486                        b,
487                    )
488                }
489                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
490                    !ty_known_to_outlive(tcx, gat_def_id, param_env, &FxIndexSet::default(), a, b)
491                }
492                _ => bug!("Unexpected ClauseKind"),
493            })
494            .map(|clause| clause.to_string())
495            .collect();
496
497        if !unsatisfied_bounds.is_empty() {
498            let plural = pluralize!(unsatisfied_bounds.len());
499            let suggestion = format!(
500                "{} {}",
501                gat_item_hir.generics.add_where_or_trailing_comma(),
502                unsatisfied_bounds.join(", "),
503            );
504            let bound =
505                if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
506            tcx.dcx()
507                .struct_span_err(
508                    gat_item_hir.span,
509                    format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
510                )
511                .with_span_suggestion(
512                    gat_item_hir.generics.tail_span_for_predicate_suggestion(),
513                    format!("add the required where clause{plural}"),
514                    suggestion,
515                    Applicability::MachineApplicable,
516                )
517                .with_note(format!(
518                    "{bound} currently required to ensure that impls have maximum flexibility"
519                ))
520                .with_note(
521                    "we are soliciting feedback, see issue #87479 \
522                     <https://github.com/rust-lang/rust/issues/87479> for more information",
523                )
524                .emit();
525        }
526    }
527}
528
529/// Add a new set of predicates to the caller_bounds of an existing param_env.
530fn augment_param_env<'tcx>(
531    tcx: TyCtxt<'tcx>,
532    param_env: ty::ParamEnv<'tcx>,
533    new_predicates: Option<&FxIndexSet<ty::Clause<'tcx>>>,
534) -> ty::ParamEnv<'tcx> {
535    let Some(new_predicates) = new_predicates else {
536        return param_env;
537    };
538
539    if new_predicates.is_empty() {
540        return param_env;
541    }
542
543    let bounds = tcx.mk_clauses_from_iter(
544        param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()),
545    );
546    // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
547    // i.e. traits::normalize_param_env_or_error
548    ty::ParamEnv::new(bounds)
549}
550
551/// We use the following trait as an example throughout this function.
552/// Specifically, let's assume that `to_check` here is the return type
553/// of `into_iter`, and the GAT we are checking this for is `Iter`.
554/// ```rust,ignore (this code fails due to this lint)
555/// trait IntoIter {
556///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
557///     type Item<'a>;
558///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
559/// }
560/// ```
561fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
562    tcx: TyCtxt<'tcx>,
563    param_env: ty::ParamEnv<'tcx>,
564    item_def_id: LocalDefId,
565    to_check: T,
566    wf_tys: &FxIndexSet<Ty<'tcx>>,
567    gat_def_id: LocalDefId,
568    gat_generics: &'tcx ty::Generics,
569) -> Option<FxIndexSet<ty::Clause<'tcx>>> {
570    // The bounds we that we would require from `to_check`
571    let mut bounds = FxIndexSet::default();
572
573    let (regions, types) = GATArgsCollector::visit(gat_def_id.to_def_id(), to_check);
574
575    // If both regions and types are empty, then this GAT isn't in the
576    // set of types we are checking, and we shouldn't try to do clause analysis
577    // (particularly, doing so would end up with an empty set of clauses,
578    // since the current method would require none, and we take the
579    // intersection of requirements of all methods)
580    if types.is_empty() && regions.is_empty() {
581        return None;
582    }
583
584    for (region_a, region_a_idx) in &regions {
585        // Ignore `'static` lifetimes for the purpose of this lint: it's
586        // because we know it outlives everything and so doesn't give meaningful
587        // clues. Also ignore `ReError`, to avoid knock-down errors.
588        if let ty::ReStatic | ty::ReError(_) = region_a.kind() {
589            continue;
590        }
591        // For each region argument (e.g., `'a` in our example), check for a
592        // relationship to the type arguments (e.g., `Self`). If there is an
593        // outlives relationship (`Self: 'a`), then we want to ensure that is
594        // reflected in a where clause on the GAT itself.
595        for (ty, ty_idx) in &types {
596            // In our example, requires that `Self: 'a`
597            if ty_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *ty, *region_a) {
598                debug!(?ty_idx, ?region_a_idx);
599                debug!("required clause: {ty} must outlive {region_a}");
600                // Translate into the generic parameters of the GAT. In
601                // our example, the type was `Self`, which will also be
602                // `Self` in the GAT.
603                let ty_param = gat_generics.param_at(*ty_idx, tcx);
604                let ty_param = Ty::new_param(tcx, ty_param.index, ty_param.name);
605                // Same for the region. In our example, 'a corresponds
606                // to the 'me parameter.
607                let region_param = gat_generics.param_at(*region_a_idx, tcx);
608                let region_param = ty::Region::new_early_param(
609                    tcx,
610                    ty::EarlyParamRegion { index: region_param.index, name: region_param.name },
611                );
612                // The predicate we expect to see. (In our example,
613                // `Self: 'me`.)
614                bounds.insert(
615                    ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param))
616                        .upcast(tcx),
617                );
618            }
619        }
620
621        // For each region argument (e.g., `'a` in our example), also check for a
622        // relationship to the other region arguments. If there is an outlives
623        // relationship, then we want to ensure that is reflected in the where clause
624        // on the GAT itself.
625        for (region_b, region_b_idx) in &regions {
626            // Again, skip `'static` because it outlives everything. Also, we trivially
627            // know that a region outlives itself. Also ignore `ReError`, to avoid
628            // knock-down errors.
629            if matches!(region_b.kind(), ty::ReStatic | ty::ReError(_)) || region_a == region_b {
630                continue;
631            }
632            if region_known_to_outlive(tcx, item_def_id, param_env, wf_tys, *region_a, *region_b) {
633                debug!(?region_a_idx, ?region_b_idx);
634                debug!("required clause: {region_a} must outlive {region_b}");
635                // Translate into the generic parameters of the GAT.
636                let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
637                let region_a_param = ty::Region::new_early_param(
638                    tcx,
639                    ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name },
640                );
641                // Same for the region.
642                let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
643                let region_b_param = ty::Region::new_early_param(
644                    tcx,
645                    ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name },
646                );
647                // The predicate we expect to see.
648                bounds.insert(
649                    ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
650                        region_a_param,
651                        region_b_param,
652                    ))
653                    .upcast(tcx),
654                );
655            }
656        }
657    }
658
659    Some(bounds)
660}
661
662/// Given a known `param_env` and a set of well formed types, can we prove that
663/// `ty` outlives `region`.
664fn ty_known_to_outlive<'tcx>(
665    tcx: TyCtxt<'tcx>,
666    id: LocalDefId,
667    param_env: ty::ParamEnv<'tcx>,
668    wf_tys: &FxIndexSet<Ty<'tcx>>,
669    ty: Ty<'tcx>,
670    region: ty::Region<'tcx>,
671) -> bool {
672    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
673        infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
674            sub_region: region,
675            sup_type: ty,
676            origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
677        });
678    })
679}
680
681/// Given a known `param_env` and a set of well formed types, can we prove that
682/// `region_a` outlives `region_b`
683fn region_known_to_outlive<'tcx>(
684    tcx: TyCtxt<'tcx>,
685    id: LocalDefId,
686    param_env: ty::ParamEnv<'tcx>,
687    wf_tys: &FxIndexSet<Ty<'tcx>>,
688    region_a: ty::Region<'tcx>,
689    region_b: ty::Region<'tcx>,
690) -> bool {
691    test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
692        infcx.sub_regions(
693            SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
694            region_b,
695            region_a,
696        );
697    })
698}
699
700/// Given a known `param_env` and a set of well formed types, set up an
701/// `InferCtxt`, call the passed function (to e.g. set up region constraints
702/// to be tested), then resolve region and return errors
703fn test_region_obligations<'tcx>(
704    tcx: TyCtxt<'tcx>,
705    id: LocalDefId,
706    param_env: ty::ParamEnv<'tcx>,
707    wf_tys: &FxIndexSet<Ty<'tcx>>,
708    add_constraints: impl FnOnce(&InferCtxt<'tcx>),
709) -> bool {
710    // Unfortunately, we have to use a new `InferCtxt` each call, because
711    // region constraints get added and solved there and we need to test each
712    // call individually.
713    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
714
715    add_constraints(&infcx);
716
717    let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
718    debug!(?errors, "errors");
719
720    // If we were able to prove that the type outlives the region without
721    // an error, it must be because of the implied or explicit bounds...
722    errors.is_empty()
723}
724
725/// TypeVisitor that looks for uses of GATs like
726/// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
727/// the two vectors, `regions` and `types` (depending on their kind). For each
728/// parameter `Pi` also track the index `i`.
729struct GATArgsCollector<'tcx> {
730    gat: DefId,
731    // Which region appears and which parameter index its instantiated with
732    regions: FxIndexSet<(ty::Region<'tcx>, usize)>,
733    // Which params appears and which parameter index its instantiated with
734    types: FxIndexSet<(Ty<'tcx>, usize)>,
735}
736
737impl<'tcx> GATArgsCollector<'tcx> {
738    fn visit<T: TypeFoldable<TyCtxt<'tcx>>>(
739        gat: DefId,
740        t: T,
741    ) -> (FxIndexSet<(ty::Region<'tcx>, usize)>, FxIndexSet<(Ty<'tcx>, usize)>) {
742        let mut visitor =
743            GATArgsCollector { gat, regions: FxIndexSet::default(), types: FxIndexSet::default() };
744        t.visit_with(&mut visitor);
745        (visitor.regions, visitor.types)
746    }
747}
748
749impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATArgsCollector<'tcx> {
750    fn visit_ty(&mut self, t: Ty<'tcx>) {
751        match t.kind() {
752            ty::Alias(ty::Projection, p) if p.def_id == self.gat => {
753                for (idx, arg) in p.args.iter().enumerate() {
754                    match arg.kind() {
755                        GenericArgKind::Lifetime(lt) if !lt.is_bound() => {
756                            self.regions.insert((lt, idx));
757                        }
758                        GenericArgKind::Type(t) => {
759                            self.types.insert((t, idx));
760                        }
761                        _ => {}
762                    }
763                }
764            }
765            _ => {}
766        }
767        t.super_visit_with(self)
768    }
769}
770
771fn lint_item_shadowing_supertrait_item<'tcx>(tcx: TyCtxt<'tcx>, trait_item_def_id: LocalDefId) {
772    let item_name = tcx.item_name(trait_item_def_id.to_def_id());
773    let trait_def_id = tcx.local_parent(trait_item_def_id);
774
775    let shadowed: Vec<_> = traits::supertrait_def_ids(tcx, trait_def_id.to_def_id())
776        .skip(1)
777        .flat_map(|supertrait_def_id| {
778            tcx.associated_items(supertrait_def_id).filter_by_name_unhygienic(item_name)
779        })
780        .collect();
781    if !shadowed.is_empty() {
782        let shadowee = if let [shadowed] = shadowed[..] {
783            errors::SupertraitItemShadowee::Labeled {
784                span: tcx.def_span(shadowed.def_id),
785                supertrait: tcx.item_name(shadowed.trait_container(tcx).unwrap()),
786            }
787        } else {
788            let (traits, spans): (Vec<_>, Vec<_>) = shadowed
789                .iter()
790                .map(|item| {
791                    (tcx.item_name(item.trait_container(tcx).unwrap()), tcx.def_span(item.def_id))
792                })
793                .unzip();
794            errors::SupertraitItemShadowee::Several { traits: traits.into(), spans: spans.into() }
795        };
796
797        tcx.emit_node_span_lint(
798            SUPERTRAIT_ITEM_SHADOWING_DEFINITION,
799            tcx.local_def_id_to_hir_id(trait_item_def_id),
800            tcx.def_span(trait_item_def_id),
801            errors::SupertraitItemShadowing {
802                item: item_name,
803                subtrait: tcx.item_name(trait_def_id.to_def_id()),
804                shadowee,
805            },
806        );
807    }
808}
809
810fn check_param_wf(tcx: TyCtxt<'_>, param: &ty::GenericParamDef) -> Result<(), ErrorGuaranteed> {
811    match param.kind {
812        // We currently only check wf of const params here.
813        ty::GenericParamDefKind::Lifetime | ty::GenericParamDefKind::Type { .. } => Ok(()),
814
815        // Const parameters are well formed if their type is structural match.
816        ty::GenericParamDefKind::Const { .. } => {
817            let ty = tcx.type_of(param.def_id).instantiate_identity();
818            let span = tcx.def_span(param.def_id);
819            let def_id = param.def_id.expect_local();
820
821            if tcx.features().unsized_const_params() {
822                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
823                    wfcx.register_bound(
824                        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
825                        wfcx.param_env,
826                        ty,
827                        tcx.require_lang_item(LangItem::UnsizedConstParamTy, span),
828                    );
829                    Ok(())
830                })
831            } else if tcx.features().adt_const_params() {
832                enter_wf_checking_ctxt(tcx, tcx.local_parent(def_id), |wfcx| {
833                    wfcx.register_bound(
834                        ObligationCause::new(span, def_id, ObligationCauseCode::ConstParam(ty)),
835                        wfcx.param_env,
836                        ty,
837                        tcx.require_lang_item(LangItem::ConstParamTy, span),
838                    );
839                    Ok(())
840                })
841            } else {
842                let span = || {
843                    let hir::GenericParamKind::Const { ty: &hir::Ty { span, .. }, .. } =
844                        tcx.hir_node_by_def_id(def_id).expect_generic_param().kind
845                    else {
846                        bug!()
847                    };
848                    span
849                };
850                let mut diag = match ty.kind() {
851                    ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
852                    ty::FnPtr(..) => tcx.dcx().struct_span_err(
853                        span(),
854                        "using function pointers as const generic parameters is forbidden",
855                    ),
856                    ty::RawPtr(_, _) => tcx.dcx().struct_span_err(
857                        span(),
858                        "using raw pointers as const generic parameters is forbidden",
859                    ),
860                    _ => {
861                        // Avoid showing "{type error}" to users. See #118179.
862                        ty.error_reported()?;
863
864                        tcx.dcx().struct_span_err(
865                            span(),
866                            format!(
867                                "`{ty}` is forbidden as the type of a const generic parameter",
868                            ),
869                        )
870                    }
871                };
872
873                diag.note("the only supported types are integers, `bool`, and `char`");
874
875                let cause = ObligationCause::misc(span(), def_id);
876                let adt_const_params_feature_string =
877                    " more complex and user defined types".to_string();
878                let may_suggest_feature = match type_allowed_to_implement_const_param_ty(
879                    tcx,
880                    tcx.param_env(param.def_id),
881                    ty,
882                    LangItem::ConstParamTy,
883                    cause,
884                ) {
885                    // Can never implement `ConstParamTy`, don't suggest anything.
886                    Err(
887                        ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed
888                        | ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(..),
889                    ) => None,
890                    Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
891                        Some(vec![
892                            (adt_const_params_feature_string, sym::adt_const_params),
893                            (
894                                " references to implement the `ConstParamTy` trait".into(),
895                                sym::unsized_const_params,
896                            ),
897                        ])
898                    }
899                    // May be able to implement `ConstParamTy`. Only emit the feature help
900                    // if the type is local, since the user may be able to fix the local type.
901                    Err(ConstParamTyImplementationError::InfrigingFields(..)) => {
902                        fn ty_is_local(ty: Ty<'_>) -> bool {
903                            match ty.kind() {
904                                ty::Adt(adt_def, ..) => adt_def.did().is_local(),
905                                // Arrays and slices use the inner type's `ConstParamTy`.
906                                ty::Array(ty, ..) | ty::Slice(ty) => ty_is_local(*ty),
907                                // `&` references use the inner type's `ConstParamTy`.
908                                // `&mut` are not supported.
909                                ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty),
910                                // Say that a tuple is local if any of its components are local.
911                                // This is not strictly correct, but it's likely that the user can fix the local component.
912                                ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)),
913                                _ => false,
914                            }
915                        }
916
917                        ty_is_local(ty).then_some(vec![(
918                            adt_const_params_feature_string,
919                            sym::adt_const_params,
920                        )])
921                    }
922                    // Implements `ConstParamTy`, suggest adding the feature to enable.
923                    Ok(..) => Some(vec![(adt_const_params_feature_string, sym::adt_const_params)]),
924                };
925                if let Some(features) = may_suggest_feature {
926                    tcx.disabled_nightly_features(&mut diag, features);
927                }
928
929                Err(diag.emit())
930            }
931        }
932    }
933}
934
935#[instrument(level = "debug", skip(tcx))]
936pub(crate) fn check_associated_item(
937    tcx: TyCtxt<'_>,
938    item_id: LocalDefId,
939) -> Result<(), ErrorGuaranteed> {
940    let loc = Some(WellFormedLoc::Ty(item_id));
941    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
942        let item = tcx.associated_item(item_id);
943
944        // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
945        // other `Foo` impls are incoherent.
946        tcx.ensure_ok()
947            .coherent_trait(tcx.parent(item.trait_item_def_id.unwrap_or(item_id.into())))?;
948
949        let self_ty = match item.container {
950            ty::AssocItemContainer::Trait => tcx.types.self_param,
951            ty::AssocItemContainer::Impl => {
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::AssocItemContainer::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_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(super) fn check_static_item(
1183    tcx: TyCtxt<'_>,
1184    item_id: LocalDefId,
1185) -> Result<(), ErrorGuaranteed> {
1186    enter_wf_checking_ctxt(tcx, item_id, |wfcx| {
1187        let ty = tcx.type_of(item_id).instantiate_identity();
1188        let item_ty = wfcx.deeply_normalize(DUMMY_SP, Some(WellFormedLoc::Ty(item_id)), ty);
1189
1190        let is_foreign_item = tcx.is_foreign_item(item_id);
1191
1192        let forbid_unsized = !is_foreign_item || {
1193            let tail = tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env));
1194            !matches!(tail.kind(), ty::Foreign(_))
1195        };
1196
1197        wfcx.register_wf_obligation(DUMMY_SP, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1198        if forbid_unsized {
1199            let span = tcx.def_span(item_id);
1200            wfcx.register_bound(
1201                traits::ObligationCause::new(
1202                    span,
1203                    wfcx.body_def_id,
1204                    ObligationCauseCode::SizedConstOrStatic,
1205                ),
1206                wfcx.param_env,
1207                item_ty,
1208                tcx.require_lang_item(LangItem::Sized, span),
1209            );
1210        }
1211
1212        // Ensure that the end result is `Sync` in a non-thread local `static`.
1213        let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1214            == Some(hir::Mutability::Not)
1215            && !is_foreign_item
1216            && !tcx.is_thread_local_static(item_id.to_def_id());
1217
1218        if should_check_for_sync {
1219            let span = tcx.def_span(item_id);
1220            wfcx.register_bound(
1221                traits::ObligationCause::new(
1222                    span,
1223                    wfcx.body_def_id,
1224                    ObligationCauseCode::SharedStatic,
1225                ),
1226                wfcx.param_env,
1227                item_ty,
1228                tcx.require_lang_item(LangItem::Sync, span),
1229            );
1230        }
1231        Ok(())
1232    })
1233}
1234
1235fn check_const_item(
1236    tcx: TyCtxt<'_>,
1237    def_id: LocalDefId,
1238    ty_span: Span,
1239) -> Result<(), ErrorGuaranteed> {
1240    enter_wf_checking_ctxt(tcx, def_id, |wfcx| {
1241        let ty = tcx.type_of(def_id).instantiate_identity();
1242        let ty = wfcx.deeply_normalize(ty_span, Some(WellFormedLoc::Ty(def_id)), ty);
1243
1244        wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(def_id)), ty.into());
1245        wfcx.register_bound(
1246            traits::ObligationCause::new(
1247                ty_span,
1248                wfcx.body_def_id,
1249                ObligationCauseCode::SizedConstOrStatic,
1250            ),
1251            wfcx.param_env,
1252            ty,
1253            tcx.require_lang_item(LangItem::Sized, ty_span),
1254        );
1255
1256        check_where_clauses(wfcx, def_id);
1257
1258        Ok(())
1259    })
1260}
1261
1262#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))]
1263fn check_impl<'tcx>(
1264    tcx: TyCtxt<'tcx>,
1265    item: &'tcx hir::Item<'tcx>,
1266    hir_self_ty: &hir::Ty<'_>,
1267    hir_trait_ref: &Option<hir::TraitRef<'_>>,
1268) -> Result<(), ErrorGuaranteed> {
1269    enter_wf_checking_ctxt(tcx, item.owner_id.def_id, |wfcx| {
1270        match hir_trait_ref {
1271            Some(hir_trait_ref) => {
1272                // `#[rustc_reservation_impl]` impls are not real impls and
1273                // therefore don't need to be WF (the trait's `Self: Trait` predicate
1274                // won't hold).
1275                let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity();
1276                // Avoid bogus "type annotations needed `Foo: Bar`" errors on `impl Bar for Foo` in case
1277                // other `Foo` impls are incoherent.
1278                tcx.ensure_ok().coherent_trait(trait_ref.def_id)?;
1279                let trait_span = hir_trait_ref.path.span;
1280                let trait_ref = wfcx.deeply_normalize(
1281                    trait_span,
1282                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1283                    trait_ref,
1284                );
1285                let trait_pred =
1286                    ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive };
1287                let mut obligations = traits::wf::trait_obligations(
1288                    wfcx.infcx,
1289                    wfcx.param_env,
1290                    wfcx.body_def_id,
1291                    trait_pred,
1292                    trait_span,
1293                    item,
1294                );
1295                for obligation in &mut obligations {
1296                    if obligation.cause.span != trait_span {
1297                        // We already have a better span.
1298                        continue;
1299                    }
1300                    if let Some(pred) = obligation.predicate.as_trait_clause()
1301                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1302                    {
1303                        obligation.cause.span = hir_self_ty.span;
1304                    }
1305                    if let Some(pred) = obligation.predicate.as_projection_clause()
1306                        && pred.skip_binder().self_ty() == trait_ref.self_ty()
1307                    {
1308                        obligation.cause.span = hir_self_ty.span;
1309                    }
1310                }
1311
1312                // Ensure that the `[const]` where clauses of the trait hold for the impl.
1313                if tcx.is_conditionally_const(item.owner_id.def_id) {
1314                    for (bound, _) in
1315                        tcx.const_conditions(trait_ref.def_id).instantiate(tcx, trait_ref.args)
1316                    {
1317                        let bound = wfcx.normalize(
1318                            item.span,
1319                            Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1320                            bound,
1321                        );
1322                        wfcx.register_obligation(Obligation::new(
1323                            tcx,
1324                            ObligationCause::new(
1325                                hir_self_ty.span,
1326                                wfcx.body_def_id,
1327                                ObligationCauseCode::WellFormed(None),
1328                            ),
1329                            wfcx.param_env,
1330                            bound.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1331                        ))
1332                    }
1333                }
1334
1335                debug!(?obligations);
1336                wfcx.register_obligations(obligations);
1337            }
1338            None => {
1339                let self_ty = tcx.type_of(item.owner_id).instantiate_identity();
1340                let self_ty = wfcx.deeply_normalize(
1341                    item.span,
1342                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1343                    self_ty,
1344                );
1345                wfcx.register_wf_obligation(
1346                    hir_self_ty.span,
1347                    Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)),
1348                    self_ty.into(),
1349                );
1350            }
1351        }
1352
1353        check_where_clauses(wfcx, item.owner_id.def_id);
1354        Ok(())
1355    })
1356}
1357
1358/// Checks where-clauses and inline bounds that are declared on `def_id`.
1359#[instrument(level = "debug", skip(wfcx))]
1360pub(super) fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, def_id: LocalDefId) {
1361    let infcx = wfcx.infcx;
1362    let tcx = wfcx.tcx();
1363
1364    let predicates = tcx.predicates_of(def_id.to_def_id());
1365    let generics = tcx.generics_of(def_id);
1366
1367    // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1368    // For example, this forbids the declaration:
1369    //
1370    //     struct Foo<T = Vec<[u32]>> { .. }
1371    //
1372    // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1373    for param in &generics.own_params {
1374        if let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity) {
1375            // Ignore dependent defaults -- that is, where the default of one type
1376            // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1377            // be sure if it will error or not as user might always specify the other.
1378            // FIXME(generic_const_exprs): This is incorrect when dealing with unused const params.
1379            // E.g: `struct Foo<const N: usize, const M: usize = { 1 - 2 }>;`. Here, we should
1380            // eagerly error but we don't as we have `ConstKind::Unevaluated(.., [N, M])`.
1381            if !default.has_param() {
1382                wfcx.register_wf_obligation(
1383                    tcx.def_span(param.def_id),
1384                    matches!(param.kind, GenericParamDefKind::Type { .. })
1385                        .then(|| WellFormedLoc::Ty(param.def_id.expect_local())),
1386                    default.as_term().unwrap(),
1387                );
1388            } else {
1389                // If we've got a generic const parameter we still want to check its
1390                // type is correct in case both it and the param type are fully concrete.
1391                let GenericArgKind::Const(ct) = default.kind() else {
1392                    continue;
1393                };
1394
1395                let ct_ty = match ct.kind() {
1396                    ty::ConstKind::Infer(_)
1397                    | ty::ConstKind::Placeholder(_)
1398                    | ty::ConstKind::Bound(_, _) => unreachable!(),
1399                    ty::ConstKind::Error(_) | ty::ConstKind::Expr(_) => continue,
1400                    ty::ConstKind::Value(cv) => cv.ty,
1401                    ty::ConstKind::Unevaluated(uv) => {
1402                        infcx.tcx.type_of(uv.def).instantiate(infcx.tcx, uv.args)
1403                    }
1404                    ty::ConstKind::Param(param_ct) => {
1405                        param_ct.find_const_ty_from_env(wfcx.param_env)
1406                    }
1407                };
1408
1409                let param_ty = tcx.type_of(param.def_id).instantiate_identity();
1410                if !ct_ty.has_param() && !param_ty.has_param() {
1411                    let cause = traits::ObligationCause::new(
1412                        tcx.def_span(param.def_id),
1413                        wfcx.body_def_id,
1414                        ObligationCauseCode::WellFormed(None),
1415                    );
1416                    wfcx.register_obligation(Obligation::new(
1417                        tcx,
1418                        cause,
1419                        wfcx.param_env,
1420                        ty::ClauseKind::ConstArgHasType(ct, param_ty),
1421                    ));
1422                }
1423            }
1424        }
1425    }
1426
1427    // Check that trait predicates are WF when params are instantiated with their defaults.
1428    // We don't want to overly constrain the predicates that may be written but we want to
1429    // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1430    // Therefore we check if a predicate which contains a single type param
1431    // with a concrete default is WF with that default instantiated.
1432    // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1433    //
1434    // First we build the defaulted generic parameters.
1435    let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| {
1436        if param.index >= generics.parent_count as u32
1437            // If the param has a default, ...
1438            && let Some(default) = param.default_value(tcx).map(ty::EarlyBinder::instantiate_identity)
1439            // ... and it's not a dependent default, ...
1440            && !default.has_param()
1441        {
1442            // ... then instantiate it with the default.
1443            return default;
1444        }
1445        tcx.mk_param_from_def(param)
1446    });
1447
1448    // Now we build the instantiated predicates.
1449    let default_obligations = predicates
1450        .predicates
1451        .iter()
1452        .flat_map(|&(pred, sp)| {
1453            #[derive(Default)]
1454            struct CountParams {
1455                params: FxHashSet<u32>,
1456            }
1457            impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams {
1458                type Result = ControlFlow<()>;
1459                fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
1460                    if let ty::Param(param) = t.kind() {
1461                        self.params.insert(param.index);
1462                    }
1463                    t.super_visit_with(self)
1464                }
1465
1466                fn visit_region(&mut self, _: ty::Region<'tcx>) -> Self::Result {
1467                    ControlFlow::Break(())
1468                }
1469
1470                fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1471                    if let ty::ConstKind::Param(param) = c.kind() {
1472                        self.params.insert(param.index);
1473                    }
1474                    c.super_visit_with(self)
1475                }
1476            }
1477            let mut param_count = CountParams::default();
1478            let has_region = pred.visit_with(&mut param_count).is_break();
1479            let instantiated_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args);
1480            // Don't check non-defaulted params, dependent defaults (including lifetimes)
1481            // or preds with multiple params.
1482            if instantiated_pred.has_non_region_param()
1483                || param_count.params.len() > 1
1484                || has_region
1485            {
1486                None
1487            } else if predicates.predicates.iter().any(|&(p, _)| p == instantiated_pred) {
1488                // Avoid duplication of predicates that contain no parameters, for example.
1489                None
1490            } else {
1491                Some((instantiated_pred, sp))
1492            }
1493        })
1494        .map(|(pred, sp)| {
1495            // Convert each of those into an obligation. So if you have
1496            // something like `struct Foo<T: Copy = String>`, we would
1497            // take that predicate `T: Copy`, instantiated with `String: Copy`
1498            // (actually that happens in the previous `flat_map` call),
1499            // and then try to prove it (in this case, we'll fail).
1500            //
1501            // Note the subtle difference from how we handle `predicates`
1502            // below: there, we are not trying to prove those predicates
1503            // to be *true* but merely *well-formed*.
1504            let pred = wfcx.normalize(sp, None, pred);
1505            let cause = traits::ObligationCause::new(
1506                sp,
1507                wfcx.body_def_id,
1508                ObligationCauseCode::WhereClause(def_id.to_def_id(), DUMMY_SP),
1509            );
1510            Obligation::new(tcx, cause, wfcx.param_env, pred)
1511        });
1512
1513    let predicates = predicates.instantiate_identity(tcx);
1514
1515    assert_eq!(predicates.predicates.len(), predicates.spans.len());
1516    let wf_obligations = predicates.into_iter().flat_map(|(p, sp)| {
1517        let p = wfcx.normalize(sp, None, p);
1518        traits::wf::clause_obligations(infcx, wfcx.param_env, wfcx.body_def_id, p, sp)
1519    });
1520    let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1521    wfcx.register_obligations(obligations);
1522}
1523
1524#[instrument(level = "debug", skip(wfcx, hir_decl))]
1525fn check_fn_or_method<'tcx>(
1526    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1527    sig: ty::PolyFnSig<'tcx>,
1528    hir_decl: &hir::FnDecl<'_>,
1529    def_id: LocalDefId,
1530) {
1531    let tcx = wfcx.tcx();
1532    let mut sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1533
1534    // Normalize the input and output types one at a time, using a different
1535    // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1536    // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1537    // for each type, preventing the HIR wf check from generating
1538    // a nice error message.
1539    let arg_span =
1540        |idx| hir_decl.inputs.get(idx).map_or(hir_decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
1541
1542    sig.inputs_and_output =
1543        tcx.mk_type_list_from_iter(sig.inputs_and_output.iter().enumerate().map(|(idx, ty)| {
1544            wfcx.deeply_normalize(
1545                arg_span(idx),
1546                Some(WellFormedLoc::Param {
1547                    function: def_id,
1548                    // Note that the `param_idx` of the output type is
1549                    // one greater than the index of the last input type.
1550                    param_idx: idx,
1551                }),
1552                ty,
1553            )
1554        }));
1555
1556    for (idx, ty) in sig.inputs_and_output.iter().enumerate() {
1557        wfcx.register_wf_obligation(
1558            arg_span(idx),
1559            Some(WellFormedLoc::Param { function: def_id, param_idx: idx }),
1560            ty.into(),
1561        );
1562    }
1563
1564    check_where_clauses(wfcx, def_id);
1565
1566    if sig.abi == ExternAbi::RustCall {
1567        let span = tcx.def_span(def_id);
1568        let has_implicit_self = hir_decl.implicit_self != hir::ImplicitSelfKind::None;
1569        let mut inputs = sig.inputs().iter().skip(if has_implicit_self { 1 } else { 0 });
1570        // Check that the argument is a tuple and is sized
1571        if let Some(ty) = inputs.next() {
1572            wfcx.register_bound(
1573                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1574                wfcx.param_env,
1575                *ty,
1576                tcx.require_lang_item(hir::LangItem::Tuple, span),
1577            );
1578            wfcx.register_bound(
1579                ObligationCause::new(span, wfcx.body_def_id, ObligationCauseCode::RustCall),
1580                wfcx.param_env,
1581                *ty,
1582                tcx.require_lang_item(hir::LangItem::Sized, span),
1583            );
1584        } else {
1585            tcx.dcx().span_err(
1586                hir_decl.inputs.last().map_or(span, |input| input.span),
1587                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1588            );
1589        }
1590        // No more inputs other than the `self` type and the tuple type
1591        if inputs.next().is_some() {
1592            tcx.dcx().span_err(
1593                hir_decl.inputs.last().map_or(span, |input| input.span),
1594                "functions with the \"rust-call\" ABI must take a single non-self tuple argument",
1595            );
1596        }
1597    }
1598
1599    // If the function has a body, additionally require that the return type is sized.
1600    check_sized_if_body(
1601        wfcx,
1602        def_id,
1603        sig.output(),
1604        match hir_decl.output {
1605            hir::FnRetTy::Return(ty) => Some(ty.span),
1606            hir::FnRetTy::DefaultReturn(_) => None,
1607        },
1608        ObligationCauseCode::SizedReturnType,
1609    );
1610}
1611
1612fn check_sized_if_body<'tcx>(
1613    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1614    def_id: LocalDefId,
1615    ty: Ty<'tcx>,
1616    maybe_span: Option<Span>,
1617    code: ObligationCauseCode<'tcx>,
1618) {
1619    let tcx = wfcx.tcx();
1620    if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
1621        let span = maybe_span.unwrap_or(body.value.span);
1622
1623        wfcx.register_bound(
1624            ObligationCause::new(span, def_id, code),
1625            wfcx.param_env,
1626            ty,
1627            tcx.require_lang_item(LangItem::Sized, span),
1628        );
1629    }
1630}
1631
1632/// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`.
1633#[derive(Clone, Copy, PartialEq)]
1634enum ArbitrarySelfTypesLevel {
1635    Basic,        // just arbitrary_self_types
1636    WithPointers, // both arbitrary_self_types and arbitrary_self_types_pointers
1637}
1638
1639#[instrument(level = "debug", skip(wfcx))]
1640fn check_method_receiver<'tcx>(
1641    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1642    fn_sig: &hir::FnSig<'_>,
1643    method: ty::AssocItem,
1644    self_ty: Ty<'tcx>,
1645) -> Result<(), ErrorGuaranteed> {
1646    let tcx = wfcx.tcx();
1647
1648    if !method.is_method() {
1649        return Ok(());
1650    }
1651
1652    let span = fn_sig.decl.inputs[0].span;
1653    let loc = Some(WellFormedLoc::Param { function: method.def_id.expect_local(), param_idx: 0 });
1654
1655    let sig = tcx.fn_sig(method.def_id).instantiate_identity();
1656    let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1657    let sig = wfcx.normalize(DUMMY_SP, loc, sig);
1658
1659    debug!("check_method_receiver: sig={:?}", sig);
1660
1661    let self_ty = wfcx.normalize(DUMMY_SP, loc, self_ty);
1662
1663    let receiver_ty = sig.inputs()[0];
1664    let receiver_ty = wfcx.normalize(DUMMY_SP, loc, receiver_ty);
1665
1666    // If the receiver already has errors reported, consider it valid to avoid
1667    // unnecessary errors (#58712).
1668    if receiver_ty.references_error() {
1669        return Ok(());
1670    }
1671
1672    let arbitrary_self_types_level = if tcx.features().arbitrary_self_types_pointers() {
1673        Some(ArbitrarySelfTypesLevel::WithPointers)
1674    } else if tcx.features().arbitrary_self_types() {
1675        Some(ArbitrarySelfTypesLevel::Basic)
1676    } else {
1677        None
1678    };
1679    let generics = tcx.generics_of(method.def_id);
1680
1681    let receiver_validity =
1682        receiver_is_valid(wfcx, span, receiver_ty, self_ty, arbitrary_self_types_level, generics);
1683    if let Err(receiver_validity_err) = receiver_validity {
1684        return Err(match arbitrary_self_types_level {
1685            // Wherever possible, emit a message advising folks that the features
1686            // `arbitrary_self_types` or `arbitrary_self_types_pointers` might
1687            // have helped.
1688            None if receiver_is_valid(
1689                wfcx,
1690                span,
1691                receiver_ty,
1692                self_ty,
1693                Some(ArbitrarySelfTypesLevel::Basic),
1694                generics,
1695            )
1696            .is_ok() =>
1697            {
1698                // Report error; would have worked with `arbitrary_self_types`.
1699                feature_err(
1700                    &tcx.sess,
1701                    sym::arbitrary_self_types,
1702                    span,
1703                    format!(
1704                        "`{receiver_ty}` cannot be used as the type of `self` without \
1705                            the `arbitrary_self_types` feature",
1706                    ),
1707                )
1708                .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1709                .emit()
1710            }
1711            None | Some(ArbitrarySelfTypesLevel::Basic)
1712                if receiver_is_valid(
1713                    wfcx,
1714                    span,
1715                    receiver_ty,
1716                    self_ty,
1717                    Some(ArbitrarySelfTypesLevel::WithPointers),
1718                    generics,
1719                )
1720                .is_ok() =>
1721            {
1722                // Report error; would have worked with `arbitrary_self_types_pointers`.
1723                feature_err(
1724                    &tcx.sess,
1725                    sym::arbitrary_self_types_pointers,
1726                    span,
1727                    format!(
1728                        "`{receiver_ty}` cannot be used as the type of `self` without \
1729                            the `arbitrary_self_types_pointers` feature",
1730                    ),
1731                )
1732                .with_help(fluent::hir_analysis_invalid_receiver_ty_help)
1733                .emit()
1734            }
1735            _ =>
1736            // Report error; would not have worked with `arbitrary_self_types[_pointers]`.
1737            {
1738                match receiver_validity_err {
1739                    ReceiverValidityError::DoesNotDeref if arbitrary_self_types_level.is_some() => {
1740                        let hint = match receiver_ty
1741                            .builtin_deref(false)
1742                            .unwrap_or(receiver_ty)
1743                            .ty_adt_def()
1744                            .and_then(|adt_def| tcx.get_diagnostic_name(adt_def.did()))
1745                        {
1746                            Some(sym::RcWeak | sym::ArcWeak) => Some(InvalidReceiverTyHint::Weak),
1747                            Some(sym::NonNull) => Some(InvalidReceiverTyHint::NonNull),
1748                            _ => None,
1749                        };
1750
1751                        tcx.dcx().emit_err(errors::InvalidReceiverTy { span, receiver_ty, hint })
1752                    }
1753                    ReceiverValidityError::DoesNotDeref => {
1754                        tcx.dcx().emit_err(errors::InvalidReceiverTyNoArbitrarySelfTypes {
1755                            span,
1756                            receiver_ty,
1757                        })
1758                    }
1759                    ReceiverValidityError::MethodGenericParamUsed => {
1760                        tcx.dcx().emit_err(errors::InvalidGenericReceiverTy { span, receiver_ty })
1761                    }
1762                }
1763            }
1764        });
1765    }
1766    Ok(())
1767}
1768
1769/// Error cases which may be returned from `receiver_is_valid`. These error
1770/// cases are generated in this function as they may be unearthed as we explore
1771/// the `autoderef` chain, but they're converted to diagnostics in the caller.
1772enum ReceiverValidityError {
1773    /// The self type does not get to the receiver type by following the
1774    /// autoderef chain.
1775    DoesNotDeref,
1776    /// A type was found which is a method type parameter, and that's not allowed.
1777    MethodGenericParamUsed,
1778}
1779
1780/// Confirms that a type is not a type parameter referring to one of the
1781/// method's type params.
1782fn confirm_type_is_not_a_method_generic_param(
1783    ty: Ty<'_>,
1784    method_generics: &ty::Generics,
1785) -> Result<(), ReceiverValidityError> {
1786    if let ty::Param(param) = ty.kind() {
1787        if (param.index as usize) >= method_generics.parent_count {
1788            return Err(ReceiverValidityError::MethodGenericParamUsed);
1789        }
1790    }
1791    Ok(())
1792}
1793
1794/// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1795/// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1796/// through a `*const/mut T` raw pointer if  `arbitrary_self_types_pointers` is also enabled.
1797/// If neither feature is enabled, the requirements are more strict: `receiver_ty` must implement
1798/// `Receiver` and directly implement `Deref<Target = self_ty>`.
1799///
1800/// N.B., there are cases this function returns `true` but causes an error to be emitted,
1801/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1802/// wrong lifetime. Be careful of this if you are calling this function speculatively.
1803fn receiver_is_valid<'tcx>(
1804    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1805    span: Span,
1806    receiver_ty: Ty<'tcx>,
1807    self_ty: Ty<'tcx>,
1808    arbitrary_self_types_enabled: Option<ArbitrarySelfTypesLevel>,
1809    method_generics: &ty::Generics,
1810) -> Result<(), ReceiverValidityError> {
1811    let infcx = wfcx.infcx;
1812    let tcx = wfcx.tcx();
1813    let cause =
1814        ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
1815
1816    // Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
1817    if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1818        let ocx = ObligationCtxt::new(wfcx.infcx);
1819        ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
1820        if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1821    }) {
1822        return Ok(());
1823    }
1824
1825    confirm_type_is_not_a_method_generic_param(receiver_ty, method_generics)?;
1826
1827    let mut autoderef = Autoderef::new(infcx, wfcx.param_env, wfcx.body_def_id, span, receiver_ty);
1828
1829    // The `arbitrary_self_types` feature allows custom smart pointer
1830    // types to be method receivers, as identified by following the Receiver<Target=T>
1831    // chain.
1832    if arbitrary_self_types_enabled.is_some() {
1833        autoderef = autoderef.use_receiver_trait();
1834    }
1835
1836    // The `arbitrary_self_types_pointers` feature allows raw pointer receivers like `self: *const Self`.
1837    if arbitrary_self_types_enabled == Some(ArbitrarySelfTypesLevel::WithPointers) {
1838        autoderef = autoderef.include_raw_pointers();
1839    }
1840
1841    // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1842    while let Some((potential_self_ty, _)) = autoderef.next() {
1843        debug!(
1844            "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1845            potential_self_ty, self_ty
1846        );
1847
1848        confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?;
1849
1850        // Check if the self type unifies. If it does, then commit the result
1851        // since it may have region side-effects.
1852        if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
1853            let ocx = ObligationCtxt::new(wfcx.infcx);
1854            ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
1855            if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
1856        }) {
1857            wfcx.register_obligations(autoderef.into_obligations());
1858            return Ok(());
1859        }
1860
1861        // Without `feature(arbitrary_self_types)`, we require that each step in the
1862        // deref chain implement `LegacyReceiver`.
1863        if arbitrary_self_types_enabled.is_none() {
1864            let legacy_receiver_trait_def_id =
1865                tcx.require_lang_item(LangItem::LegacyReceiver, span);
1866            if !legacy_receiver_is_implemented(
1867                wfcx,
1868                legacy_receiver_trait_def_id,
1869                cause.clone(),
1870                potential_self_ty,
1871            ) {
1872                // We cannot proceed.
1873                break;
1874            }
1875
1876            // Register the bound, in case it has any region side-effects.
1877            wfcx.register_bound(
1878                cause.clone(),
1879                wfcx.param_env,
1880                potential_self_ty,
1881                legacy_receiver_trait_def_id,
1882            );
1883        }
1884    }
1885
1886    debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1887    Err(ReceiverValidityError::DoesNotDeref)
1888}
1889
1890fn legacy_receiver_is_implemented<'tcx>(
1891    wfcx: &WfCheckingCtxt<'_, 'tcx>,
1892    legacy_receiver_trait_def_id: DefId,
1893    cause: ObligationCause<'tcx>,
1894    receiver_ty: Ty<'tcx>,
1895) -> bool {
1896    let tcx = wfcx.tcx();
1897    let trait_ref = ty::TraitRef::new(tcx, legacy_receiver_trait_def_id, [receiver_ty]);
1898
1899    let obligation = Obligation::new(tcx, cause, wfcx.param_env, trait_ref);
1900
1901    if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1902        true
1903    } else {
1904        debug!(
1905            "receiver_is_implemented: type `{:?}` does not implement `LegacyReceiver` trait",
1906            receiver_ty
1907        );
1908        false
1909    }
1910}
1911
1912pub(super) fn check_variances_for_type_defn<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) {
1913    match tcx.def_kind(def_id) {
1914        DefKind::Enum | DefKind::Struct | DefKind::Union => {
1915            // Ok
1916        }
1917        DefKind::TyAlias => {
1918            assert!(
1919                tcx.type_alias_is_lazy(def_id),
1920                "should not be computing variance of non-free type alias"
1921            );
1922        }
1923        kind => span_bug!(tcx.def_span(def_id), "cannot compute the variances of {kind:?}"),
1924    }
1925
1926    let ty_predicates = tcx.predicates_of(def_id);
1927    assert_eq!(ty_predicates.parent, None);
1928    let variances = tcx.variances_of(def_id);
1929
1930    let mut constrained_parameters: FxHashSet<_> = variances
1931        .iter()
1932        .enumerate()
1933        .filter(|&(_, &variance)| variance != ty::Bivariant)
1934        .map(|(index, _)| Parameter(index as u32))
1935        .collect();
1936
1937    identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1938
1939    // Lazily calculated because it is only needed in case of an error.
1940    let explicitly_bounded_params = LazyCell::new(|| {
1941        let icx = crate::collect::ItemCtxt::new(tcx, def_id);
1942        tcx.hir_node_by_def_id(def_id)
1943            .generics()
1944            .unwrap()
1945            .predicates
1946            .iter()
1947            .filter_map(|predicate| match predicate.kind {
1948                hir::WherePredicateKind::BoundPredicate(predicate) => {
1949                    match icx.lower_ty(predicate.bounded_ty).kind() {
1950                        ty::Param(data) => Some(Parameter(data.index)),
1951                        _ => None,
1952                    }
1953                }
1954                _ => None,
1955            })
1956            .collect::<FxHashSet<_>>()
1957    });
1958
1959    for (index, _) in variances.iter().enumerate() {
1960        let parameter = Parameter(index as u32);
1961
1962        if constrained_parameters.contains(&parameter) {
1963            continue;
1964        }
1965
1966        let node = tcx.hir_node_by_def_id(def_id);
1967        let item = node.expect_item();
1968        let hir_generics = node.generics().unwrap();
1969        let hir_param = &hir_generics.params[index];
1970
1971        let ty_param = &tcx.generics_of(item.owner_id).own_params[index];
1972
1973        if ty_param.def_id != hir_param.def_id.into() {
1974            // Valid programs always have lifetimes before types in the generic parameter list.
1975            // ty_generics are normalized to be in this required order, and variances are built
1976            // from ty generics, not from hir generics. but we need hir generics to get
1977            // a span out.
1978            //
1979            // If they aren't in the same order, then the user has written invalid code, and already
1980            // got an error about it (or I'm wrong about this).
1981            tcx.dcx().span_delayed_bug(
1982                hir_param.span,
1983                "hir generics and ty generics in different order",
1984            );
1985            continue;
1986        }
1987
1988        // Look for `ErrorGuaranteed` deeply within this type.
1989        if let ControlFlow::Break(ErrorGuaranteed { .. }) = tcx
1990            .type_of(def_id)
1991            .instantiate_identity()
1992            .visit_with(&mut HasErrorDeep { tcx, seen: Default::default() })
1993        {
1994            continue;
1995        }
1996
1997        match hir_param.name {
1998            hir::ParamName::Error(_) => {
1999                // Don't report a bivariance error for a lifetime that isn't
2000                // even valid to name.
2001            }
2002            _ => {
2003                let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
2004                report_bivariance(tcx, hir_param, has_explicit_bounds, item);
2005            }
2006        }
2007    }
2008}
2009
2010/// Look for `ErrorGuaranteed` deeply within structs' (unsubstituted) fields.
2011struct HasErrorDeep<'tcx> {
2012    tcx: TyCtxt<'tcx>,
2013    seen: FxHashSet<DefId>,
2014}
2015impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for HasErrorDeep<'tcx> {
2016    type Result = ControlFlow<ErrorGuaranteed>;
2017
2018    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
2019        match *ty.kind() {
2020            ty::Adt(def, _) => {
2021                if self.seen.insert(def.did()) {
2022                    for field in def.all_fields() {
2023                        self.tcx.type_of(field.did).instantiate_identity().visit_with(self)?;
2024                    }
2025                }
2026            }
2027            ty::Error(guar) => return ControlFlow::Break(guar),
2028            _ => {}
2029        }
2030        ty.super_visit_with(self)
2031    }
2032
2033    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
2034        if let Err(guar) = r.error_reported() {
2035            ControlFlow::Break(guar)
2036        } else {
2037            ControlFlow::Continue(())
2038        }
2039    }
2040
2041    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
2042        if let Err(guar) = c.error_reported() {
2043            ControlFlow::Break(guar)
2044        } else {
2045            ControlFlow::Continue(())
2046        }
2047    }
2048}
2049
2050fn report_bivariance<'tcx>(
2051    tcx: TyCtxt<'tcx>,
2052    param: &'tcx hir::GenericParam<'tcx>,
2053    has_explicit_bounds: bool,
2054    item: &'tcx hir::Item<'tcx>,
2055) -> ErrorGuaranteed {
2056    let param_name = param.name.ident();
2057
2058    let help = match item.kind {
2059        ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
2060            if let Some(def_id) = tcx.lang_items().phantom_data() {
2061                errors::UnusedGenericParameterHelp::Adt {
2062                    param_name,
2063                    phantom_data: tcx.def_path_str(def_id),
2064                }
2065            } else {
2066                errors::UnusedGenericParameterHelp::AdtNoPhantomData { param_name }
2067            }
2068        }
2069        ItemKind::TyAlias(..) => errors::UnusedGenericParameterHelp::TyAlias { param_name },
2070        item_kind => bug!("report_bivariance: unexpected item kind: {item_kind:?}"),
2071    };
2072
2073    let mut usage_spans = vec![];
2074    intravisit::walk_item(
2075        &mut CollectUsageSpans { spans: &mut usage_spans, param_def_id: param.def_id.to_def_id() },
2076        item,
2077    );
2078
2079    if !usage_spans.is_empty() {
2080        // First, check if the ADT/LTA is (probably) cyclical. We say probably here, since we're
2081        // not actually looking into substitutions, just walking through fields / the "RHS".
2082        // We don't recurse into the hidden types of opaques or anything else fancy.
2083        let item_def_id = item.owner_id.to_def_id();
2084        let is_probably_cyclical =
2085            IsProbablyCyclical { tcx, item_def_id, seen: Default::default() }
2086                .visit_def(item_def_id)
2087                .is_break();
2088        // If the ADT/LTA is cyclical, then if at least one usage of the type parameter or
2089        // the `Self` alias is present in the, then it's probably a cyclical struct/ type
2090        // alias, and we should call those parameter usages recursive rather than just saying
2091        // they're unused...
2092        //
2093        // We currently report *all* of the parameter usages, since computing the exact
2094        // subset is very involved, and the fact we're mentioning recursion at all is
2095        // likely to guide the user in the right direction.
2096        if is_probably_cyclical {
2097            return tcx.dcx().emit_err(errors::RecursiveGenericParameter {
2098                spans: usage_spans,
2099                param_span: param.span,
2100                param_name,
2101                param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2102                help,
2103                note: (),
2104            });
2105        }
2106    }
2107
2108    let const_param_help =
2109        matches!(param.kind, hir::GenericParamKind::Type { .. } if !has_explicit_bounds);
2110
2111    let mut diag = tcx.dcx().create_err(errors::UnusedGenericParameter {
2112        span: param.span,
2113        param_name,
2114        param_def_kind: tcx.def_descr(param.def_id.to_def_id()),
2115        usage_spans,
2116        help,
2117        const_param_help,
2118    });
2119    diag.code(E0392);
2120    diag.emit()
2121}
2122
2123/// Detects cases where an ADT/LTA is trivially cyclical -- we want to detect this so
2124/// we only mention that its parameters are used cyclically if the ADT/LTA is truly
2125/// cyclical.
2126///
2127/// Notably, we don't consider substitutions here, so this may have false positives.
2128struct IsProbablyCyclical<'tcx> {
2129    tcx: TyCtxt<'tcx>,
2130    item_def_id: DefId,
2131    seen: FxHashSet<DefId>,
2132}
2133
2134impl<'tcx> IsProbablyCyclical<'tcx> {
2135    fn visit_def(&mut self, def_id: DefId) -> ControlFlow<(), ()> {
2136        match self.tcx.def_kind(def_id) {
2137            DefKind::Struct | DefKind::Enum | DefKind::Union => {
2138                self.tcx.adt_def(def_id).all_fields().try_for_each(|field| {
2139                    self.tcx.type_of(field.did).instantiate_identity().visit_with(self)
2140                })
2141            }
2142            DefKind::TyAlias if self.tcx.type_alias_is_lazy(def_id) => {
2143                self.tcx.type_of(def_id).instantiate_identity().visit_with(self)
2144            }
2145            _ => ControlFlow::Continue(()),
2146        }
2147    }
2148}
2149
2150impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsProbablyCyclical<'tcx> {
2151    type Result = ControlFlow<(), ()>;
2152
2153    fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<(), ()> {
2154        let def_id = match ty.kind() {
2155            ty::Adt(adt_def, _) => Some(adt_def.did()),
2156            ty::Alias(ty::Free, alias_ty) => Some(alias_ty.def_id),
2157            _ => None,
2158        };
2159        if let Some(def_id) = def_id {
2160            if def_id == self.item_def_id {
2161                return ControlFlow::Break(());
2162            }
2163            if self.seen.insert(def_id) {
2164                self.visit_def(def_id)?;
2165            }
2166        }
2167        ty.super_visit_with(self)
2168    }
2169}
2170
2171/// Collect usages of the `param_def_id` and `Res::SelfTyAlias` in the HIR.
2172///
2173/// This is used to report places where the user has used parameters in a
2174/// non-variance-constraining way for better bivariance errors.
2175struct CollectUsageSpans<'a> {
2176    spans: &'a mut Vec<Span>,
2177    param_def_id: DefId,
2178}
2179
2180impl<'tcx> Visitor<'tcx> for CollectUsageSpans<'_> {
2181    type Result = ();
2182
2183    fn visit_generics(&mut self, _g: &'tcx rustc_hir::Generics<'tcx>) -> Self::Result {
2184        // Skip the generics. We only care about fields, not where clause/param bounds.
2185    }
2186
2187    fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result {
2188        if let hir::TyKind::Path(hir::QPath::Resolved(None, qpath)) = t.kind {
2189            if let Res::Def(DefKind::TyParam, def_id) = qpath.res
2190                && def_id == self.param_def_id
2191            {
2192                self.spans.push(t.span);
2193                return;
2194            } else if let Res::SelfTyAlias { .. } = qpath.res {
2195                self.spans.push(t.span);
2196                return;
2197            }
2198        }
2199        intravisit::walk_ty(self, t);
2200    }
2201}
2202
2203impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
2204    /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
2205    /// aren't true.
2206    #[instrument(level = "debug", skip(self))]
2207    fn check_false_global_bounds(&mut self) {
2208        let tcx = self.ocx.infcx.tcx;
2209        let mut span = tcx.def_span(self.body_def_id);
2210        let empty_env = ty::ParamEnv::empty();
2211
2212        let predicates_with_span = tcx.predicates_of(self.body_def_id).predicates.iter().copied();
2213        // Check elaborated bounds.
2214        let implied_obligations = traits::elaborate(tcx, predicates_with_span);
2215
2216        for (pred, obligation_span) in implied_obligations {
2217            // We lower empty bounds like `Vec<dyn Copy>:` as
2218            // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
2219            // regular WF checking
2220            if let ty::ClauseKind::WellFormed(..) = pred.kind().skip_binder() {
2221                continue;
2222            }
2223            // Match the existing behavior.
2224            if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) {
2225                let pred = self.normalize(span, None, pred);
2226
2227                // only use the span of the predicate clause (#90869)
2228                let hir_node = tcx.hir_node_by_def_id(self.body_def_id);
2229                if let Some(hir::Generics { predicates, .. }) = hir_node.generics() {
2230                    span = predicates
2231                        .iter()
2232                        // There seems to be no better way to find out which predicate we are in
2233                        .find(|pred| pred.span.contains(obligation_span))
2234                        .map(|pred| pred.span)
2235                        .unwrap_or(obligation_span);
2236                }
2237
2238                let obligation = Obligation::new(
2239                    tcx,
2240                    traits::ObligationCause::new(
2241                        span,
2242                        self.body_def_id,
2243                        ObligationCauseCode::TrivialBound,
2244                    ),
2245                    empty_env,
2246                    pred,
2247                );
2248                self.ocx.register_obligation(obligation);
2249            }
2250        }
2251    }
2252}
2253
2254pub(super) fn check_type_wf(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> {
2255    let items = tcx.hir_crate_items(());
2256    let res = items
2257        .par_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id))
2258        .and(items.par_impl_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2259        .and(items.par_trait_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)))
2260        .and(
2261            items.par_foreign_items(|item| tcx.ensure_ok().check_well_formed(item.owner_id.def_id)),
2262        )
2263        .and(items.par_nested_bodies(|item| tcx.ensure_ok().check_well_formed(item)))
2264        .and(items.par_opaques(|item| tcx.ensure_ok().check_well_formed(item)));
2265    super::entry::check_for_entry_fn(tcx);
2266
2267    res
2268}
2269
2270fn lint_redundant_lifetimes<'tcx>(
2271    tcx: TyCtxt<'tcx>,
2272    owner_id: LocalDefId,
2273    outlives_env: &OutlivesEnvironment<'tcx>,
2274) {
2275    let def_kind = tcx.def_kind(owner_id);
2276    match def_kind {
2277        DefKind::Struct
2278        | DefKind::Union
2279        | DefKind::Enum
2280        | DefKind::Trait
2281        | DefKind::TraitAlias
2282        | DefKind::Fn
2283        | DefKind::Const
2284        | DefKind::Impl { of_trait: _ } => {
2285            // Proceed
2286        }
2287        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
2288            let parent_def_id = tcx.local_parent(owner_id);
2289            if matches!(tcx.def_kind(parent_def_id), DefKind::Impl { of_trait: true }) {
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}