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