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