]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/wfcheck.rs
use `pluralize!`
[rust.git] / compiler / rustc_typeck / src / check / wfcheck.rs
1 use crate::check::regionck::OutlivesEnvironmentExt;
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
3 use rustc_ast as ast;
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
6 use rustc_hir as hir;
7 use rustc_hir::def_id::{DefId, LocalDefId};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir::ItemKind;
10 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
11 use rustc_infer::infer::outlives::obligations::TypeOutlives;
12 use rustc_infer::infer::region_constraints::GenericKind;
13 use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
14 use rustc_infer::traits::Normalized;
15 use rustc_middle::ty::query::Providers;
16 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
17 use rustc_middle::ty::trait_def::TraitSpecializationKind;
18 use rustc_middle::ty::{
19     self, AdtKind, DefIdTree, EarlyBinder, GenericParamDefKind, ToPredicate, Ty, TyCtxt,
20     TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitor,
21 };
22 use rustc_session::parse::feature_err;
23 use rustc_span::symbol::{sym, Ident, Symbol};
24 use rustc_span::{Span, DUMMY_SP};
25 use rustc_trait_selection::autoderef::Autoderef;
26 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
27 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
28 use rustc_trait_selection::traits::query::normalize::AtExt;
29 use rustc_trait_selection::traits::query::NoSolution;
30 use rustc_trait_selection::traits::{
31     self, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc,
32 };
33
34 use std::cell::LazyCell;
35 use std::convert::TryInto;
36 use std::iter;
37 use std::ops::{ControlFlow, Deref};
38
39 pub(super) struct WfCheckingCtxt<'a, 'tcx> {
40     pub(super) ocx: ObligationCtxt<'a, 'tcx>,
41     span: Span,
42     body_id: hir::HirId,
43     param_env: ty::ParamEnv<'tcx>,
44 }
45 impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
46     type Target = ObligationCtxt<'a, 'tcx>;
47     fn deref(&self) -> &Self::Target {
48         &self.ocx
49     }
50 }
51
52 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
53     fn tcx(&self) -> TyCtxt<'tcx> {
54         self.ocx.infcx.tcx
55     }
56
57     fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
58     where
59         T: TypeFoldable<'tcx>,
60     {
61         self.ocx.normalize(
62             ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc)),
63             self.param_env,
64             value,
65         )
66     }
67
68     fn register_wf_obligation(
69         &self,
70         span: Span,
71         loc: Option<WellFormedLoc>,
72         arg: ty::GenericArg<'tcx>,
73     ) {
74         let cause =
75             traits::ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc));
76         self.ocx.register_obligation(traits::Obligation::new(
77             cause,
78             self.param_env,
79             ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx()),
80         ));
81     }
82 }
83
84 pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
85     tcx: TyCtxt<'tcx>,
86     span: Span,
87     body_def_id: LocalDefId,
88     f: F,
89 ) where
90     F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> FxHashSet<Ty<'tcx>>,
91 {
92     let param_env = tcx.param_env(body_def_id);
93     let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id);
94     tcx.infer_ctxt().enter(|ref infcx| {
95         let ocx = ObligationCtxt::new(infcx);
96         let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env };
97
98         if !tcx.features().trivial_bounds {
99             wfcx.check_false_global_bounds()
100         }
101         let wf_tys = f(&mut wfcx);
102         let errors = wfcx.select_all_or_error();
103         if !errors.is_empty() {
104             infcx.report_fulfillment_errors(&errors, None, false);
105             return;
106         }
107
108         let mut outlives_environment = OutlivesEnvironment::new(param_env);
109         outlives_environment.add_implied_bounds(infcx, wf_tys, body_id);
110         infcx.check_region_obligations_and_report_errors(body_def_id, &outlives_environment);
111     })
112 }
113
114 fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
115     let node = tcx.hir().expect_owner(def_id);
116     match node {
117         hir::OwnerNode::Crate(_) => {}
118         hir::OwnerNode::Item(item) => check_item(tcx, item),
119         hir::OwnerNode::TraitItem(item) => check_trait_item(tcx, item),
120         hir::OwnerNode::ImplItem(item) => check_impl_item(tcx, item),
121         hir::OwnerNode::ForeignItem(item) => check_foreign_item(tcx, item),
122     }
123
124     if let Some(generics) = node.generics() {
125         for param in generics.params {
126             check_param_wf(tcx, param)
127         }
128     }
129 }
130
131 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
132 /// well-formed, meaning that they do not require any constraints not declared in the struct
133 /// definition itself. For example, this definition would be illegal:
134 ///
135 /// ```rust
136 /// struct Ref<'a, T> { x: &'a T }
137 /// ```
138 ///
139 /// because the type did not declare that `T:'a`.
140 ///
141 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
142 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
143 /// the types first.
144 #[instrument(skip(tcx), level = "debug")]
145 fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
146     let def_id = item.def_id;
147
148     debug!(
149         ?item.def_id,
150         item.name = ? tcx.def_path_str(def_id.to_def_id())
151     );
152
153     match item.kind {
154         // Right now we check that every default trait implementation
155         // has an implementation of itself. Basically, a case like:
156         //
157         //     impl Trait for T {}
158         //
159         // has a requirement of `T: Trait` which was required for default
160         // method implementations. Although this could be improved now that
161         // there's a better infrastructure in place for this, it's being left
162         // for a follow-up work.
163         //
164         // Since there's such a requirement, we need to check *just* positive
165         // implementations, otherwise things like:
166         //
167         //     impl !Send for T {}
168         //
169         // won't be allowed unless there's an *explicit* implementation of `Send`
170         // for `T`
171         hir::ItemKind::Impl(ref impl_) => {
172             let is_auto = tcx
173                 .impl_trait_ref(item.def_id)
174                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
175             if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
176                 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
177                 let mut err =
178                     tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
179                 err.span_labels(impl_.defaultness_span, "default because of this");
180                 err.span_label(sp, "auto trait");
181                 err.emit();
182             }
183             // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
184             match (tcx.impl_polarity(def_id), impl_.polarity) {
185                 (ty::ImplPolarity::Positive, _) => {
186                     check_impl(tcx, item, impl_.self_ty, &impl_.of_trait, impl_.constness);
187                 }
188                 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
189                     // FIXME(#27579): what amount of WF checking do we need for neg impls?
190                     if let hir::Defaultness::Default { .. } = impl_.defaultness {
191                         let mut spans = vec![span];
192                         spans.extend(impl_.defaultness_span);
193                         struct_span_err!(
194                             tcx.sess,
195                             spans,
196                             E0750,
197                             "negative impls cannot be default impls"
198                         )
199                         .emit();
200                     }
201                 }
202                 (ty::ImplPolarity::Reservation, _) => {
203                     // FIXME: what amount of WF checking do we need for reservation impls?
204                 }
205                 _ => unreachable!(),
206             }
207         }
208         hir::ItemKind::Fn(ref sig, ..) => {
209             check_item_fn(tcx, item.def_id, item.ident, item.span, sig.decl);
210         }
211         hir::ItemKind::Static(ty, ..) => {
212             check_item_type(tcx, item.def_id, ty.span, false);
213         }
214         hir::ItemKind::Const(ty, ..) => {
215             check_item_type(tcx, item.def_id, ty.span, false);
216         }
217         hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
218             check_type_defn(tcx, item, false, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
219
220             check_variances_for_type_defn(tcx, item, ast_generics);
221         }
222         hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
223             check_type_defn(tcx, item, true, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
224
225             check_variances_for_type_defn(tcx, item, ast_generics);
226         }
227         hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
228             check_type_defn(tcx, item, true, |wfcx| wfcx.enum_variants(enum_def));
229
230             check_variances_for_type_defn(tcx, item, ast_generics);
231         }
232         hir::ItemKind::Trait(..) => {
233             check_trait(tcx, item);
234         }
235         hir::ItemKind::TraitAlias(..) => {
236             check_trait(tcx, item);
237         }
238         // `ForeignItem`s are handled separately.
239         hir::ItemKind::ForeignMod { .. } => {}
240         _ => {}
241     }
242 }
243
244 fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) {
245     let def_id = item.def_id;
246
247     debug!(
248         ?item.def_id,
249         item.name = ? tcx.def_path_str(def_id.to_def_id())
250     );
251
252     match item.kind {
253         hir::ForeignItemKind::Fn(decl, ..) => {
254             check_item_fn(tcx, item.def_id, item.ident, item.span, decl)
255         }
256         hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, item.def_id, ty.span, true),
257         hir::ForeignItemKind::Type => (),
258     }
259 }
260
261 fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) {
262     let def_id = trait_item.def_id;
263
264     let (method_sig, span) = match trait_item.kind {
265         hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
266         hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
267         _ => (None, trait_item.span),
268     };
269     check_object_unsafe_self_trait_by_name(tcx, trait_item);
270     check_associated_item(tcx, trait_item.def_id, span, method_sig);
271
272     let encl_trait_def_id = tcx.local_parent(def_id);
273     let encl_trait = tcx.hir().expect_item(encl_trait_def_id);
274     let encl_trait_def_id = encl_trait.def_id.to_def_id();
275     let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
276         Some("fn")
277     } else if Some(encl_trait_def_id) == tcx.lang_items().fn_mut_trait() {
278         Some("fn_mut")
279     } else {
280         None
281     };
282
283     if let (Some(fn_lang_item_name), "call") =
284         (fn_lang_item_name, trait_item.ident.name.to_ident_string().as_str())
285     {
286         // We are looking at the `call` function of the `fn` or `fn_mut` lang item.
287         // Do some rudimentary sanity checking to avoid an ICE later (issue #83471).
288         if let Some(hir::FnSig { decl, span, .. }) = method_sig {
289             if let [self_ty, _] = decl.inputs {
290                 if !matches!(self_ty.kind, hir::TyKind::Rptr(_, _)) {
291                     tcx.sess
292                         .struct_span_err(
293                             self_ty.span,
294                             &format!(
295                                 "first argument of `call` in `{fn_lang_item_name}` lang item must be a reference",
296                             ),
297                         )
298                         .emit();
299                 }
300             } else {
301                 tcx.sess
302                     .struct_span_err(
303                         *span,
304                         &format!(
305                             "`call` function in `{fn_lang_item_name}` lang item takes exactly two arguments",
306                         ),
307                     )
308                     .emit();
309             }
310         } else {
311             tcx.sess
312                 .struct_span_err(
313                     trait_item.span,
314                     &format!(
315                         "`call` trait item in `{fn_lang_item_name}` lang item must be a function",
316                     ),
317                 )
318                 .emit();
319         }
320     }
321 }
322
323 /// Require that the user writes where clauses on GATs for the implicit
324 /// outlives bounds involving trait parameters in trait functions and
325 /// lifetimes passed as GAT substs. See `self-outlives-lint` test.
326 ///
327 /// We use the following trait as an example throughout this function:
328 /// ```rust,ignore (this code fails due to this lint)
329 /// trait IntoIter {
330 ///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
331 ///     type Item<'a>;
332 ///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
333 /// }
334 /// ```
335 fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRef]) {
336     // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
337     let mut required_bounds_by_item = FxHashMap::default();
338
339     // Loop over all GATs together, because if this lint suggests adding a where-clause bound
340     // to one GAT, it might then require us to an additional bound on another GAT.
341     // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
342     // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
343     // those GATs.
344     loop {
345         let mut should_continue = false;
346         for gat_item in associated_items {
347             let gat_def_id = gat_item.id.def_id;
348             let gat_item = tcx.associated_item(gat_def_id);
349             // If this item is not an assoc ty, or has no substs, then it's not a GAT
350             if gat_item.kind != ty::AssocKind::Type {
351                 continue;
352             }
353             let gat_generics = tcx.generics_of(gat_def_id);
354             // FIXME(jackh726): we can also warn in the more general case
355             if gat_generics.params.is_empty() {
356                 continue;
357             }
358
359             // Gather the bounds with which all other items inside of this trait constrain the GAT.
360             // This is calculated by taking the intersection of the bounds that each item
361             // constrains the GAT with individually.
362             let mut new_required_bounds: Option<FxHashSet<ty::Predicate<'_>>> = None;
363             for item in associated_items {
364                 let item_def_id = item.id.def_id;
365                 // Skip our own GAT, since it does not constrain itself at all.
366                 if item_def_id == gat_def_id {
367                     continue;
368                 }
369
370                 let item_hir_id = item.id.hir_id();
371                 let param_env = tcx.param_env(item_def_id);
372
373                 let item_required_bounds = match item.kind {
374                     // In our example, this corresponds to `into_iter` method
375                     hir::AssocItemKind::Fn { .. } => {
376                         // For methods, we check the function signature's return type for any GATs
377                         // to constrain. In the `into_iter` case, we see that the return type
378                         // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
379                         let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
380                             item_def_id.to_def_id(),
381                             tcx.fn_sig(item_def_id),
382                         );
383                         gather_gat_bounds(
384                             tcx,
385                             param_env,
386                             item_hir_id,
387                             sig.output(),
388                             // We also assume that all of the function signature's parameter types
389                             // are well formed.
390                             &sig.inputs().iter().copied().collect(),
391                             gat_def_id,
392                             gat_generics,
393                         )
394                     }
395                     // In our example, this corresponds to the `Iter` and `Item` associated types
396                     hir::AssocItemKind::Type => {
397                         // If our associated item is a GAT with missing bounds, add them to
398                         // the param-env here. This allows this GAT to propagate missing bounds
399                         // to other GATs.
400                         let param_env = augment_param_env(
401                             tcx,
402                             param_env,
403                             required_bounds_by_item.get(&item_def_id),
404                         );
405                         gather_gat_bounds(
406                             tcx,
407                             param_env,
408                             item_hir_id,
409                             tcx.explicit_item_bounds(item_def_id)
410                                 .iter()
411                                 .copied()
412                                 .collect::<Vec<_>>(),
413                             &FxHashSet::default(),
414                             gat_def_id,
415                             gat_generics,
416                         )
417                     }
418                     hir::AssocItemKind::Const => None,
419                 };
420
421                 if let Some(item_required_bounds) = item_required_bounds {
422                     // Take the intersection of the required bounds for this GAT, and
423                     // the item_required_bounds which are the ones implied by just
424                     // this item alone.
425                     // This is why we use an Option<_>, since we need to distinguish
426                     // the empty set of bounds from the _uninitialized_ set of bounds.
427                     if let Some(new_required_bounds) = &mut new_required_bounds {
428                         new_required_bounds.retain(|b| item_required_bounds.contains(b));
429                     } else {
430                         new_required_bounds = Some(item_required_bounds);
431                     }
432                 }
433             }
434
435             if let Some(new_required_bounds) = new_required_bounds {
436                 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
437                 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
438                     // Iterate until our required_bounds no longer change
439                     // Since they changed here, we should continue the loop
440                     should_continue = true;
441                 }
442             }
443         }
444         // We know that this loop will eventually halt, since we only set `should_continue` if the
445         // `required_bounds` for this item grows. Since we are not creating any new region or type
446         // variables, the set of all region and type bounds that we could ever insert are limited
447         // by the number of unique types and regions we observe in a given item.
448         if !should_continue {
449             break;
450         }
451     }
452
453     for (gat_def_id, required_bounds) in required_bounds_by_item {
454         let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id);
455         debug!(?required_bounds);
456         let param_env = tcx.param_env(gat_def_id);
457         let gat_hir = gat_item_hir.hir_id();
458
459         let mut unsatisfied_bounds: Vec<_> = required_bounds
460             .into_iter()
461             .filter(|clause| match clause.kind().skip_binder() {
462                 ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
463                     !region_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
464                 }
465                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
466                     !ty_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
467                 }
468                 _ => bug!("Unexpected PredicateKind"),
469             })
470             .map(|clause| clause.to_string())
471             .collect();
472
473         // We sort so that order is predictable
474         unsatisfied_bounds.sort();
475
476         if !unsatisfied_bounds.is_empty() {
477             let plural = pluralize!(unsatisfied_bounds.len());
478             let mut err = tcx.sess.struct_span_err(
479                 gat_item_hir.span,
480                 &format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
481             );
482
483             let suggestion = format!(
484                 "{} {}",
485                 gat_item_hir.generics.add_where_or_trailing_comma(),
486                 unsatisfied_bounds.join(", "),
487             );
488             err.span_suggestion(
489                 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
490                 &format!("add the required where clause{plural}"),
491                 suggestion,
492                 Applicability::MachineApplicable,
493             );
494
495             let bound =
496                 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
497             err.note(&format!(
498                 "{} currently required to ensure that impls have maximum flexibility",
499                 bound
500             ));
501             err.note(
502                 "we are soliciting feedback, see issue #87479 \
503                  <https://github.com/rust-lang/rust/issues/87479> \
504                  for more information",
505             );
506
507             err.emit();
508         }
509     }
510 }
511
512 /// Add a new set of predicates to the caller_bounds of an existing param_env.
513 fn augment_param_env<'tcx>(
514     tcx: TyCtxt<'tcx>,
515     param_env: ty::ParamEnv<'tcx>,
516     new_predicates: Option<&FxHashSet<ty::Predicate<'tcx>>>,
517 ) -> ty::ParamEnv<'tcx> {
518     let Some(new_predicates) = new_predicates else {
519         return param_env;
520     };
521
522     if new_predicates.is_empty() {
523         return param_env;
524     }
525
526     let bounds =
527         tcx.mk_predicates(param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()));
528     // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
529     // i.e. traits::normalize_param_env_or_error
530     ty::ParamEnv::new(bounds, param_env.reveal(), param_env.constness())
531 }
532
533 /// We use the following trait as an example throughout this function.
534 /// Specifically, let's assume that `to_check` here is the return type
535 /// of `into_iter`, and the GAT we are checking this for is `Iter`.
536 /// ```rust,ignore (this code fails due to this lint)
537 /// trait IntoIter {
538 ///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
539 ///     type Item<'a>;
540 ///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
541 /// }
542 /// ```
543 fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>(
544     tcx: TyCtxt<'tcx>,
545     param_env: ty::ParamEnv<'tcx>,
546     item_hir: hir::HirId,
547     to_check: T,
548     wf_tys: &FxHashSet<Ty<'tcx>>,
549     gat_def_id: LocalDefId,
550     gat_generics: &'tcx ty::Generics,
551 ) -> Option<FxHashSet<ty::Predicate<'tcx>>> {
552     // The bounds we that we would require from `to_check`
553     let mut bounds = FxHashSet::default();
554
555     let (regions, types) = GATSubstCollector::visit(gat_def_id.to_def_id(), to_check);
556
557     // If both regions and types are empty, then this GAT isn't in the
558     // set of types we are checking, and we shouldn't try to do clause analysis
559     // (particularly, doing so would end up with an empty set of clauses,
560     // since the current method would require none, and we take the
561     // intersection of requirements of all methods)
562     if types.is_empty() && regions.is_empty() {
563         return None;
564     }
565
566     for (region_a, region_a_idx) in &regions {
567         // Ignore `'static` lifetimes for the purpose of this lint: it's
568         // because we know it outlives everything and so doesn't give meaningful
569         // clues
570         if let ty::ReStatic = **region_a {
571             continue;
572         }
573         // For each region argument (e.g., `'a` in our example), check for a
574         // relationship to the type arguments (e.g., `Self`). If there is an
575         // outlives relationship (`Self: 'a`), then we want to ensure that is
576         // reflected in a where clause on the GAT itself.
577         for (ty, ty_idx) in &types {
578             // In our example, requires that `Self: 'a`
579             if ty_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *ty, *region_a) {
580                 debug!(?ty_idx, ?region_a_idx);
581                 debug!("required clause: {ty} must outlive {region_a}");
582                 // Translate into the generic parameters of the GAT. In
583                 // our example, the type was `Self`, which will also be
584                 // `Self` in the GAT.
585                 let ty_param = gat_generics.param_at(*ty_idx, tcx);
586                 let ty_param = tcx
587                     .mk_ty(ty::Param(ty::ParamTy { index: ty_param.index, name: ty_param.name }));
588                 // Same for the region. In our example, 'a corresponds
589                 // to the 'me parameter.
590                 let region_param = gat_generics.param_at(*region_a_idx, tcx);
591                 let region_param =
592                     tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
593                         def_id: region_param.def_id,
594                         index: region_param.index,
595                         name: region_param.name,
596                     }));
597                 // The predicate we expect to see. (In our example,
598                 // `Self: 'me`.)
599                 let clause =
600                     ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param));
601                 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
602                 bounds.insert(clause);
603             }
604         }
605
606         // For each region argument (e.g., `'a` in our example), also check for a
607         // relationship to the other region arguments. If there is an outlives
608         // relationship, then we want to ensure that is reflected in the where clause
609         // on the GAT itself.
610         for (region_b, region_b_idx) in &regions {
611             // Again, skip `'static` because it outlives everything. Also, we trivially
612             // know that a region outlives itself.
613             if ty::ReStatic == **region_b || region_a == region_b {
614                 continue;
615             }
616             if region_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *region_a, *region_b) {
617                 debug!(?region_a_idx, ?region_b_idx);
618                 debug!("required clause: {region_a} must outlive {region_b}");
619                 // Translate into the generic parameters of the GAT.
620                 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
621                 let region_a_param =
622                     tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
623                         def_id: region_a_param.def_id,
624                         index: region_a_param.index,
625                         name: region_a_param.name,
626                     }));
627                 // Same for the region.
628                 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
629                 let region_b_param =
630                     tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
631                         def_id: region_b_param.def_id,
632                         index: region_b_param.index,
633                         name: region_b_param.name,
634                     }));
635                 // The predicate we expect to see.
636                 let clause = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
637                     region_a_param,
638                     region_b_param,
639                 ));
640                 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
641                 bounds.insert(clause);
642             }
643         }
644     }
645
646     Some(bounds)
647 }
648
649 /// Given a known `param_env` and a set of well formed types, can we prove that
650 /// `ty` outlives `region`.
651 fn ty_known_to_outlive<'tcx>(
652     tcx: TyCtxt<'tcx>,
653     id: hir::HirId,
654     param_env: ty::ParamEnv<'tcx>,
655     wf_tys: &FxHashSet<Ty<'tcx>>,
656     ty: Ty<'tcx>,
657     region: ty::Region<'tcx>,
658 ) -> bool {
659     resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| {
660         let origin = infer::RelateParamBound(DUMMY_SP, ty, None);
661         let outlives = &mut TypeOutlives::new(infcx, tcx, region_bound_pairs, None, param_env);
662         outlives.type_must_outlive(origin, ty, region);
663     })
664 }
665
666 /// Given a known `param_env` and a set of well formed types, can we prove that
667 /// `region_a` outlives `region_b`
668 fn region_known_to_outlive<'tcx>(
669     tcx: TyCtxt<'tcx>,
670     id: hir::HirId,
671     param_env: ty::ParamEnv<'tcx>,
672     wf_tys: &FxHashSet<Ty<'tcx>>,
673     region_a: ty::Region<'tcx>,
674     region_b: ty::Region<'tcx>,
675 ) -> bool {
676     resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |mut infcx, _| {
677         use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
678         let origin = infer::RelateRegionParamBound(DUMMY_SP);
679         // `region_a: region_b` -> `region_b <= region_a`
680         infcx.push_sub_region_constraint(origin, region_b, region_a);
681     })
682 }
683
684 /// Given a known `param_env` and a set of well formed types, set up an
685 /// `InferCtxt`, call the passed function (to e.g. set up region constraints
686 /// to be tested), then resolve region and return errors
687 fn resolve_regions_with_wf_tys<'tcx>(
688     tcx: TyCtxt<'tcx>,
689     id: hir::HirId,
690     param_env: ty::ParamEnv<'tcx>,
691     wf_tys: &FxHashSet<Ty<'tcx>>,
692     add_constraints: impl for<'a> FnOnce(
693         &'a InferCtxt<'a, 'tcx>,
694         &'a Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>,
695     ),
696 ) -> bool {
697     // Unfortunately, we have to use a new `InferCtxt` each call, because
698     // region constraints get added and solved there and we need to test each
699     // call individually.
700     tcx.infer_ctxt().enter(|infcx| {
701         let mut outlives_environment = OutlivesEnvironment::new(param_env);
702         outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id);
703         let region_bound_pairs = outlives_environment.region_bound_pairs();
704
705         add_constraints(&infcx, region_bound_pairs);
706
707         let errors = infcx.resolve_regions(&outlives_environment);
708
709         debug!(?errors, "errors");
710
711         // If we were able to prove that the type outlives the region without
712         // an error, it must be because of the implied or explicit bounds...
713         errors.is_empty()
714     })
715 }
716
717 /// TypeVisitor that looks for uses of GATs like
718 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
719 /// the two vectors, `regions` and `types` (depending on their kind). For each
720 /// parameter `Pi` also track the index `i`.
721 struct GATSubstCollector<'tcx> {
722     gat: DefId,
723     // Which region appears and which parameter index its substituted for
724     regions: FxHashSet<(ty::Region<'tcx>, usize)>,
725     // Which params appears and which parameter index its substituted for
726     types: FxHashSet<(Ty<'tcx>, usize)>,
727 }
728
729 impl<'tcx> GATSubstCollector<'tcx> {
730     fn visit<T: TypeFoldable<'tcx>>(
731         gat: DefId,
732         t: T,
733     ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
734         let mut visitor =
735             GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() };
736         t.visit_with(&mut visitor);
737         (visitor.regions, visitor.types)
738     }
739 }
740
741 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
742     type BreakTy = !;
743
744     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
745         match t.kind() {
746             ty::Projection(p) if p.item_def_id == self.gat => {
747                 for (idx, subst) in p.substs.iter().enumerate() {
748                     match subst.unpack() {
749                         GenericArgKind::Lifetime(lt) if !lt.is_late_bound() => {
750                             self.regions.insert((lt, idx));
751                         }
752                         GenericArgKind::Type(t) => {
753                             self.types.insert((t, idx));
754                         }
755                         _ => {}
756                     }
757                 }
758             }
759             _ => {}
760         }
761         t.super_visit_with(self)
762     }
763 }
764
765 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
766     match ty.kind {
767         hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
768             [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
769             _ => false,
770         },
771         _ => false,
772     }
773 }
774
775 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
776 /// When this is done, suggest using `Self` instead.
777 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
778     let (trait_name, trait_def_id) =
779         match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id())) {
780             hir::Node::Item(item) => match item.kind {
781                 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
782                 _ => return,
783             },
784             _ => return,
785         };
786     let mut trait_should_be_self = vec![];
787     match &item.kind {
788         hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
789             if could_be_self(trait_def_id, ty) =>
790         {
791             trait_should_be_self.push(ty.span)
792         }
793         hir::TraitItemKind::Fn(sig, _) => {
794             for ty in sig.decl.inputs {
795                 if could_be_self(trait_def_id, ty) {
796                     trait_should_be_self.push(ty.span);
797                 }
798             }
799             match sig.decl.output {
800                 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
801                     trait_should_be_self.push(ty.span);
802                 }
803                 _ => {}
804             }
805         }
806         _ => {}
807     }
808     if !trait_should_be_self.is_empty() {
809         if tcx.object_safety_violations(trait_def_id).is_empty() {
810             return;
811         }
812         let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
813         tcx.sess
814             .struct_span_err(
815                 trait_should_be_self,
816                 "associated item referring to unboxed trait object for its own trait",
817             )
818             .span_label(trait_name.span, "in this trait")
819             .multipart_suggestion(
820                 "you might have meant to use `Self` to refer to the implementing type",
821                 sugg,
822                 Applicability::MachineApplicable,
823             )
824             .emit();
825     }
826 }
827
828 fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) {
829     let def_id = impl_item.def_id;
830
831     let (method_sig, span) = match impl_item.kind {
832         hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
833         // Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
834         hir::ImplItemKind::TyAlias(ty) if ty.span != DUMMY_SP => (None, ty.span),
835         _ => (None, impl_item.span),
836     };
837
838     check_associated_item(tcx, def_id, span, method_sig);
839 }
840
841 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
842     match param.kind {
843         // We currently only check wf of const params here.
844         hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
845
846         // Const parameters are well formed if their type is structural match.
847         hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
848             let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
849
850             if tcx.features().adt_const_params {
851                 let err = match ty.peel_refs().kind() {
852                     ty::FnPtr(_) => Some("function pointers"),
853                     ty::RawPtr(_) => Some("raw pointers"),
854                     _ => None,
855                 };
856
857                 if let Some(unsupported_type) = err {
858                     tcx.sess.span_err(
859                         hir_ty.span,
860                         &format!(
861                             "using {} as const generic parameters is forbidden",
862                             unsupported_type
863                         ),
864                     );
865                 }
866
867                 if let Some(non_structural_match_ty) =
868                     traits::search_for_structural_match_violation(param.span, tcx, ty, false)
869                 {
870                     // We use the same error code in both branches, because this is really the same
871                     // issue: we just special-case the message for type parameters to make it
872                     // clearer.
873                     match ty.peel_refs().kind() {
874                         ty::Param(_) => {
875                             // Const parameters may not have type parameters as their types,
876                             // because we cannot be sure that the type parameter derives `PartialEq`
877                             // and `Eq` (just implementing them is not enough for `structural_match`).
878                             struct_span_err!(
879                                 tcx.sess,
880                                 hir_ty.span,
881                                 E0741,
882                                 "`{ty}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
883                                 used as the type of a const parameter",
884                             )
885                             .span_label(
886                                 hir_ty.span,
887                                 format!("`{ty}` may not derive both `PartialEq` and `Eq`"),
888                             )
889                             .note(
890                                 "it is not currently possible to use a type parameter as the type of a \
891                                 const parameter",
892                             )
893                             .emit();
894                         }
895                         ty::Float(_) => {
896                             struct_span_err!(
897                                 tcx.sess,
898                                 hir_ty.span,
899                                 E0741,
900                                 "`{ty}` is forbidden as the type of a const generic parameter",
901                             )
902                             .note("floats do not derive `Eq` or `Ord`, which are required for const parameters")
903                             .emit();
904                         }
905                         _ => {
906                             let mut diag = struct_span_err!(
907                                 tcx.sess,
908                                 hir_ty.span,
909                                 E0741,
910                                 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
911                                 the type of a const parameter",
912                                 non_structural_match_ty.ty,
913                             );
914
915                             if ty == non_structural_match_ty.ty {
916                                 diag.span_label(
917                                     hir_ty.span,
918                                     format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
919                                 );
920                             }
921
922                             diag.emit();
923                         }
924                     }
925                 }
926             } else {
927                 let err_ty_str;
928                 let mut is_ptr = true;
929
930                 let err = match ty.kind() {
931                     ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
932                     ty::FnPtr(_) => Some("function pointers"),
933                     ty::RawPtr(_) => Some("raw pointers"),
934                     _ => {
935                         is_ptr = false;
936                         err_ty_str = format!("`{ty}`");
937                         Some(err_ty_str.as_str())
938                     }
939                 };
940
941                 if let Some(unsupported_type) = err {
942                     if is_ptr {
943                         tcx.sess.span_err(
944                             hir_ty.span,
945                             &format!(
946                                 "using {unsupported_type} as const generic parameters is forbidden",
947                             ),
948                         );
949                     } else {
950                         let mut err = tcx.sess.struct_span_err(
951                             hir_ty.span,
952                             &format!(
953                                 "{unsupported_type} is forbidden as the type of a const generic parameter",
954                             ),
955                         );
956                         err.note("the only supported types are integers, `bool` and `char`");
957                         if tcx.sess.is_nightly_build() {
958                             err.help(
959                             "more complex types are supported with `#![feature(adt_const_params)]`",
960                         );
961                         }
962                         err.emit();
963                     }
964                 }
965             }
966         }
967     }
968 }
969
970 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
971 fn check_associated_item(
972     tcx: TyCtxt<'_>,
973     item_id: LocalDefId,
974     span: Span,
975     sig_if_method: Option<&hir::FnSig<'_>>,
976 ) {
977     let loc = Some(WellFormedLoc::Ty(item_id));
978     enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
979         let item = tcx.associated_item(item_id);
980
981         let (mut implied_bounds, self_ty) = match item.container {
982             ty::TraitContainer(_) => (FxHashSet::default(), tcx.types.self_param),
983             ty::ImplContainer(def_id) => (
984                 impl_implied_bounds(tcx, wfcx.param_env, def_id.expect_local(), span),
985                 tcx.type_of(def_id),
986             ),
987         };
988
989         match item.kind {
990             ty::AssocKind::Const => {
991                 let ty = tcx.type_of(item.def_id);
992                 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
993                 wfcx.register_wf_obligation(span, loc, ty.into());
994             }
995             ty::AssocKind::Fn => {
996                 let sig = tcx.fn_sig(item.def_id);
997                 let hir_sig = sig_if_method.expect("bad signature for method");
998                 check_fn_or_method(
999                     wfcx,
1000                     item.ident(tcx).span,
1001                     sig,
1002                     hir_sig.decl,
1003                     item.def_id.expect_local(),
1004                     &mut implied_bounds,
1005                 );
1006                 check_method_receiver(wfcx, hir_sig, item, self_ty);
1007             }
1008             ty::AssocKind::Type => {
1009                 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
1010                     check_associated_type_bounds(wfcx, item, span)
1011                 }
1012                 if item.defaultness.has_value() {
1013                     let ty = tcx.type_of(item.def_id);
1014                     let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1015                     wfcx.register_wf_obligation(span, loc, ty.into());
1016                 }
1017             }
1018         }
1019
1020         implied_bounds
1021     })
1022 }
1023
1024 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
1025     match kind {
1026         ItemKind::Struct(..) => Some(AdtKind::Struct),
1027         ItemKind::Union(..) => Some(AdtKind::Union),
1028         ItemKind::Enum(..) => Some(AdtKind::Enum),
1029         _ => None,
1030     }
1031 }
1032
1033 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
1034 fn check_type_defn<'tcx, F>(
1035     tcx: TyCtxt<'tcx>,
1036     item: &hir::Item<'tcx>,
1037     all_sized: bool,
1038     mut lookup_fields: F,
1039 ) where
1040     F: FnMut(&WfCheckingCtxt<'_, 'tcx>) -> Vec<AdtVariant<'tcx>>,
1041 {
1042     enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1043         let variants = lookup_fields(wfcx);
1044         let packed = tcx.adt_def(item.def_id).repr().packed();
1045
1046         for variant in &variants {
1047             // All field types must be well-formed.
1048             for field in &variant.fields {
1049                 wfcx.register_wf_obligation(
1050                     field.span,
1051                     Some(WellFormedLoc::Ty(field.def_id)),
1052                     field.ty.into(),
1053                 )
1054             }
1055
1056             // For DST, or when drop needs to copy things around, all
1057             // intermediate types must be sized.
1058             let needs_drop_copy = || {
1059                 packed && {
1060                     let ty = variant.fields.last().unwrap().ty;
1061                     let ty = tcx.erase_regions(ty);
1062                     if ty.needs_infer() {
1063                         tcx.sess
1064                             .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
1065                         // Just treat unresolved type expression as if it needs drop.
1066                         true
1067                     } else {
1068                         ty.needs_drop(tcx, tcx.param_env(item.def_id))
1069                     }
1070                 }
1071             };
1072             // All fields (except for possibly the last) should be sized.
1073             let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1074             let unsized_len = if all_sized { 0 } else { 1 };
1075             for (idx, field) in
1076                 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
1077             {
1078                 let last = idx == variant.fields.len() - 1;
1079                 wfcx.register_bound(
1080                     traits::ObligationCause::new(
1081                         field.span,
1082                         wfcx.body_id,
1083                         traits::FieldSized {
1084                             adt_kind: match item_adt_kind(&item.kind) {
1085                                 Some(i) => i,
1086                                 None => bug!(),
1087                             },
1088                             span: field.span,
1089                             last,
1090                         },
1091                     ),
1092                     wfcx.param_env,
1093                     field.ty,
1094                     tcx.require_lang_item(LangItem::Sized, None),
1095                 );
1096             }
1097
1098             // Explicit `enum` discriminant values must const-evaluate successfully.
1099             if let Some(discr_def_id) = variant.explicit_discr {
1100                 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
1101
1102                 let cause = traits::ObligationCause::new(
1103                     tcx.def_span(discr_def_id),
1104                     wfcx.body_id,
1105                     traits::MiscObligation,
1106                 );
1107                 wfcx.register_obligation(traits::Obligation::new(
1108                     cause,
1109                     wfcx.param_env,
1110                     ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
1111                         ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
1112                         discr_substs,
1113                     )))
1114                     .to_predicate(tcx),
1115                 ));
1116             }
1117         }
1118
1119         check_where_clauses(wfcx, item.span, item.def_id);
1120
1121         // No implied bounds in a struct definition.
1122         FxHashSet::default()
1123     });
1124 }
1125
1126 #[instrument(skip(tcx, item))]
1127 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
1128     debug!(?item.def_id);
1129
1130     let trait_def = tcx.trait_def(item.def_id);
1131     if trait_def.is_marker
1132         || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1133     {
1134         for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
1135             struct_span_err!(
1136                 tcx.sess,
1137                 tcx.def_span(*associated_def_id),
1138                 E0714,
1139                 "marker traits cannot have associated items",
1140             )
1141             .emit();
1142         }
1143     }
1144
1145     enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1146         check_where_clauses(wfcx, item.span, item.def_id);
1147
1148         FxHashSet::default()
1149     });
1150
1151     // Only check traits, don't check trait aliases
1152     if let hir::ItemKind::Trait(_, _, _, _, items) = item.kind {
1153         check_gat_where_clauses(tcx, items);
1154     }
1155 }
1156
1157 /// Checks all associated type defaults of trait `trait_def_id`.
1158 ///
1159 /// Assuming the defaults are used, check that all predicates (bounds on the
1160 /// assoc type and where clauses on the trait) hold.
1161 fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1162     let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1163
1164     debug!("check_associated_type_bounds: bounds={:?}", bounds);
1165     let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1166         let normalized_bound = wfcx.normalize(span, None, bound);
1167         traits::wf::predicate_obligations(
1168             wfcx.infcx,
1169             wfcx.param_env,
1170             wfcx.body_id,
1171             normalized_bound,
1172             bound_span,
1173         )
1174     });
1175
1176     wfcx.register_obligations(wf_obligations);
1177 }
1178
1179 fn check_item_fn(
1180     tcx: TyCtxt<'_>,
1181     def_id: LocalDefId,
1182     ident: Ident,
1183     span: Span,
1184     decl: &hir::FnDecl<'_>,
1185 ) {
1186     enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1187         let sig = tcx.fn_sig(def_id);
1188         let mut implied_bounds = FxHashSet::default();
1189         check_fn_or_method(wfcx, ident.span, sig, decl, def_id, &mut implied_bounds);
1190         implied_bounds
1191     })
1192 }
1193
1194 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1195     debug!("check_item_type: {:?}", item_id);
1196
1197     enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1198         let ty = tcx.type_of(item_id);
1199         let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1200
1201         let mut forbid_unsized = true;
1202         if allow_foreign_ty {
1203             let tail = tcx.struct_tail_erasing_lifetimes(item_ty, wfcx.param_env);
1204             if let ty::Foreign(_) = tail.kind() {
1205                 forbid_unsized = false;
1206             }
1207         }
1208
1209         wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
1210         if forbid_unsized {
1211             wfcx.register_bound(
1212                 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::WellFormed(None)),
1213                 wfcx.param_env,
1214                 item_ty,
1215                 tcx.require_lang_item(LangItem::Sized, None),
1216             );
1217         }
1218
1219         // Ensure that the end result is `Sync` in a non-thread local `static`.
1220         let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1221             == Some(hir::Mutability::Not)
1222             && !tcx.is_foreign_item(item_id.to_def_id())
1223             && !tcx.is_thread_local_static(item_id.to_def_id());
1224
1225         if should_check_for_sync {
1226             wfcx.register_bound(
1227                 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::SharedStatic),
1228                 wfcx.param_env,
1229                 item_ty,
1230                 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1231             );
1232         }
1233
1234         // No implied bounds in a const, etc.
1235         FxHashSet::default()
1236     });
1237 }
1238
1239 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1240 fn check_impl<'tcx>(
1241     tcx: TyCtxt<'tcx>,
1242     item: &'tcx hir::Item<'tcx>,
1243     ast_self_ty: &hir::Ty<'_>,
1244     ast_trait_ref: &Option<hir::TraitRef<'_>>,
1245     constness: hir::Constness,
1246 ) {
1247     enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1248         match *ast_trait_ref {
1249             Some(ref ast_trait_ref) => {
1250                 // `#[rustc_reservation_impl]` impls are not real impls and
1251                 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1252                 // won't hold).
1253                 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
1254                 let trait_ref = wfcx.normalize(ast_trait_ref.path.span, None, trait_ref);
1255                 let trait_pred = ty::TraitPredicate {
1256                     trait_ref,
1257                     constness: match constness {
1258                         hir::Constness::Const => ty::BoundConstness::ConstIfConst,
1259                         hir::Constness::NotConst => ty::BoundConstness::NotConst,
1260                     },
1261                     polarity: ty::ImplPolarity::Positive,
1262                 };
1263                 let obligations = traits::wf::trait_obligations(
1264                     wfcx.infcx,
1265                     wfcx.param_env,
1266                     wfcx.body_id,
1267                     &trait_pred,
1268                     ast_trait_ref.path.span,
1269                     item,
1270                 );
1271                 debug!(?obligations);
1272                 wfcx.register_obligations(obligations);
1273             }
1274             None => {
1275                 let self_ty = tcx.type_of(item.def_id);
1276                 let self_ty = wfcx.normalize(item.span, None, self_ty);
1277                 wfcx.register_wf_obligation(
1278                     ast_self_ty.span,
1279                     Some(WellFormedLoc::Ty(item.hir_id().expect_owner())),
1280                     self_ty.into(),
1281                 );
1282             }
1283         }
1284
1285         check_where_clauses(wfcx, item.span, item.def_id);
1286
1287         impl_implied_bounds(tcx, wfcx.param_env, item.def_id, item.span)
1288     });
1289 }
1290
1291 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1292 #[instrument(level = "debug", skip(wfcx))]
1293 fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1294     let infcx = wfcx.infcx;
1295     let tcx = wfcx.tcx();
1296
1297     let predicates = tcx.predicates_of(def_id);
1298     let generics = tcx.generics_of(def_id);
1299
1300     let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1301         GenericParamDefKind::Type { has_default, .. }
1302         | GenericParamDefKind::Const { has_default } => {
1303             has_default && def.index >= generics.parent_count as u32
1304         }
1305         GenericParamDefKind::Lifetime => unreachable!(),
1306     };
1307
1308     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1309     // For example, this forbids the declaration:
1310     //
1311     //     struct Foo<T = Vec<[u32]>> { .. }
1312     //
1313     // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1314     for param in &generics.params {
1315         match param.kind {
1316             GenericParamDefKind::Type { .. } => {
1317                 if is_our_default(param) {
1318                     let ty = tcx.type_of(param.def_id);
1319                     // Ignore dependent defaults -- that is, where the default of one type
1320                     // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1321                     // be sure if it will error or not as user might always specify the other.
1322                     if !ty.needs_subst() {
1323                         wfcx.register_wf_obligation(tcx.def_span(param.def_id), None, ty.into());
1324                     }
1325                 }
1326             }
1327             GenericParamDefKind::Const { .. } => {
1328                 if is_our_default(param) {
1329                     // FIXME(const_generics_defaults): This
1330                     // is incorrect when dealing with unused substs, for example
1331                     // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1332                     // we should eagerly error.
1333                     let default_ct = tcx.const_param_default(param.def_id);
1334                     if !default_ct.needs_subst() {
1335                         wfcx.register_wf_obligation(
1336                             tcx.def_span(param.def_id),
1337                             None,
1338                             default_ct.into(),
1339                         );
1340                     }
1341                 }
1342             }
1343             // Doesn't have defaults.
1344             GenericParamDefKind::Lifetime => {}
1345         }
1346     }
1347
1348     // Check that trait predicates are WF when params are substituted by their defaults.
1349     // We don't want to overly constrain the predicates that may be written but we want to
1350     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1351     // Therefore we check if a predicate which contains a single type param
1352     // with a concrete default is WF with that default substituted.
1353     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1354     //
1355     // First we build the defaulted substitution.
1356     let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| {
1357         match param.kind {
1358             GenericParamDefKind::Lifetime => {
1359                 // All regions are identity.
1360                 tcx.mk_param_from_def(param)
1361             }
1362
1363             GenericParamDefKind::Type { .. } => {
1364                 // If the param has a default, ...
1365                 if is_our_default(param) {
1366                     let default_ty = tcx.type_of(param.def_id);
1367                     // ... and it's not a dependent default, ...
1368                     if !default_ty.needs_subst() {
1369                         // ... then substitute it with the default.
1370                         return default_ty.into();
1371                     }
1372                 }
1373
1374                 tcx.mk_param_from_def(param)
1375             }
1376             GenericParamDefKind::Const { .. } => {
1377                 // If the param has a default, ...
1378                 if is_our_default(param) {
1379                     let default_ct = tcx.const_param_default(param.def_id);
1380                     // ... and it's not a dependent default, ...
1381                     if !default_ct.needs_subst() {
1382                         // ... then substitute it with the default.
1383                         return default_ct.into();
1384                     }
1385                 }
1386
1387                 tcx.mk_param_from_def(param)
1388             }
1389         }
1390     });
1391
1392     // Now we build the substituted predicates.
1393     let default_obligations = predicates
1394         .predicates
1395         .iter()
1396         .flat_map(|&(pred, sp)| {
1397             #[derive(Default)]
1398             struct CountParams {
1399                 params: FxHashSet<u32>,
1400             }
1401             impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
1402                 type BreakTy = ();
1403
1404                 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1405                     if let ty::Param(param) = t.kind() {
1406                         self.params.insert(param.index);
1407                     }
1408                     t.super_visit_with(self)
1409                 }
1410
1411                 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1412                     ControlFlow::BREAK
1413                 }
1414
1415                 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1416                     if let ty::ConstKind::Param(param) = c.kind() {
1417                         self.params.insert(param.index);
1418                     }
1419                     c.super_visit_with(self)
1420                 }
1421             }
1422             let mut param_count = CountParams::default();
1423             let has_region = pred.visit_with(&mut param_count).is_break();
1424             let substituted_pred = EarlyBinder(pred).subst(tcx, substs);
1425             // Don't check non-defaulted params, dependent defaults (including lifetimes)
1426             // or preds with multiple params.
1427             if substituted_pred.has_param_types_or_consts()
1428                 || param_count.params.len() > 1
1429                 || has_region
1430             {
1431                 None
1432             } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1433                 // Avoid duplication of predicates that contain no parameters, for example.
1434                 None
1435             } else {
1436                 Some((substituted_pred, sp))
1437             }
1438         })
1439         .map(|(pred, sp)| {
1440             // Convert each of those into an obligation. So if you have
1441             // something like `struct Foo<T: Copy = String>`, we would
1442             // take that predicate `T: Copy`, substitute to `String: Copy`
1443             // (actually that happens in the previous `flat_map` call),
1444             // and then try to prove it (in this case, we'll fail).
1445             //
1446             // Note the subtle difference from how we handle `predicates`
1447             // below: there, we are not trying to prove those predicates
1448             // to be *true* but merely *well-formed*.
1449             let pred = wfcx.normalize(sp, None, pred);
1450             let cause = traits::ObligationCause::new(
1451                 sp,
1452                 wfcx.body_id,
1453                 traits::ItemObligation(def_id.to_def_id()),
1454             );
1455             traits::Obligation::new(cause, wfcx.param_env, pred)
1456         });
1457
1458     let predicates = predicates.instantiate_identity(tcx);
1459
1460     let predicates = wfcx.normalize(span, None, predicates);
1461
1462     debug!(?predicates.predicates);
1463     assert_eq!(predicates.predicates.len(), predicates.spans.len());
1464     let wf_obligations =
1465         iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
1466             traits::wf::predicate_obligations(infcx, wfcx.param_env, wfcx.body_id, p, sp)
1467         });
1468
1469     let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1470     wfcx.register_obligations(obligations);
1471 }
1472
1473 #[tracing::instrument(level = "debug", skip(wfcx, span, hir_decl))]
1474 fn check_fn_or_method<'tcx>(
1475     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1476     span: Span,
1477     sig: ty::PolyFnSig<'tcx>,
1478     hir_decl: &hir::FnDecl<'_>,
1479     def_id: LocalDefId,
1480     implied_bounds: &mut FxHashSet<Ty<'tcx>>,
1481 ) {
1482     let tcx = wfcx.tcx();
1483     let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1484
1485     // Normalize the input and output types one at a time, using a different
1486     // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1487     // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1488     // for each type, preventing the HIR wf check from generating
1489     // a nice error message.
1490     let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1491     inputs_and_output = tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1492         wfcx.normalize(
1493             span,
1494             Some(WellFormedLoc::Param {
1495                 function: def_id,
1496                 // Note that the `param_idx` of the output type is
1497                 // one greater than the index of the last input type.
1498                 param_idx: i.try_into().unwrap(),
1499             }),
1500             ty,
1501         )
1502     }));
1503     // Manually call `normalize_associated_types_in` on the other types
1504     // in `FnSig`. This ensures that if the types of these fields
1505     // ever change to include projections, we will start normalizing
1506     // them automatically.
1507     let sig = ty::FnSig {
1508         inputs_and_output,
1509         c_variadic: wfcx.normalize(span, None, c_variadic),
1510         unsafety: wfcx.normalize(span, None, unsafety),
1511         abi: wfcx.normalize(span, None, abi),
1512     };
1513
1514     for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1515         wfcx.register_wf_obligation(
1516             ty.span,
1517             Some(WellFormedLoc::Param { function: def_id, param_idx: i.try_into().unwrap() }),
1518             input_ty.into(),
1519         );
1520     }
1521
1522     implied_bounds.extend(sig.inputs());
1523
1524     wfcx.register_wf_obligation(hir_decl.output.span(), None, sig.output().into());
1525
1526     // FIXME(#27579) return types should not be implied bounds
1527     implied_bounds.insert(sig.output());
1528
1529     debug!(?implied_bounds);
1530
1531     check_where_clauses(wfcx, span, def_id);
1532 }
1533
1534 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1535      `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1536      of the previous types except `Self`)";
1537
1538 #[tracing::instrument(level = "debug", skip(wfcx))]
1539 fn check_method_receiver<'tcx>(
1540     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1541     fn_sig: &hir::FnSig<'_>,
1542     method: &ty::AssocItem,
1543     self_ty: Ty<'tcx>,
1544 ) {
1545     let tcx = wfcx.tcx();
1546
1547     if !method.fn_has_self_parameter {
1548         return;
1549     }
1550
1551     let span = fn_sig.decl.inputs[0].span;
1552
1553     let sig = tcx.fn_sig(method.def_id);
1554     let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1555     let sig = wfcx.normalize(span, None, sig);
1556
1557     debug!("check_method_receiver: sig={:?}", sig);
1558
1559     let self_ty = wfcx.normalize(span, None, self_ty);
1560
1561     let receiver_ty = sig.inputs()[0];
1562     let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1563
1564     if tcx.features().arbitrary_self_types {
1565         if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1566             // Report error; `arbitrary_self_types` was enabled.
1567             e0307(tcx, span, receiver_ty);
1568         }
1569     } else {
1570         if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
1571             if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1572                 // Report error; would have worked with `arbitrary_self_types`.
1573                 feature_err(
1574                     &tcx.sess.parse_sess,
1575                     sym::arbitrary_self_types,
1576                     span,
1577                     &format!(
1578                         "`{receiver_ty}` cannot be used as the type of `self` without \
1579                          the `arbitrary_self_types` feature",
1580                     ),
1581                 )
1582                 .help(HELP_FOR_SELF_TYPE)
1583                 .emit();
1584             } else {
1585                 // Report error; would not have worked with `arbitrary_self_types`.
1586                 e0307(tcx, span, receiver_ty);
1587             }
1588         }
1589     }
1590 }
1591
1592 fn e0307<'tcx>(tcx: TyCtxt<'tcx>, span: Span, receiver_ty: Ty<'_>) {
1593     struct_span_err!(
1594         tcx.sess.diagnostic(),
1595         span,
1596         E0307,
1597         "invalid `self` parameter type: {receiver_ty}"
1598     )
1599     .note("type of `self` must be `Self` or a type that dereferences to it")
1600     .help(HELP_FOR_SELF_TYPE)
1601     .emit();
1602 }
1603
1604 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1605 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1606 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1607 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1608 /// `Deref<Target = self_ty>`.
1609 ///
1610 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1611 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1612 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1613 fn receiver_is_valid<'tcx>(
1614     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1615     span: Span,
1616     receiver_ty: Ty<'tcx>,
1617     self_ty: Ty<'tcx>,
1618     arbitrary_self_types_enabled: bool,
1619 ) -> bool {
1620     let infcx = wfcx.infcx;
1621     let tcx = wfcx.tcx();
1622     let cause =
1623         ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver);
1624
1625     let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
1626
1627     // `self: Self` is always valid.
1628     if can_eq_self(receiver_ty) {
1629         if let Err(err) = wfcx.equate_types(&cause, wfcx.param_env, self_ty, receiver_ty) {
1630             infcx.report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
1631         }
1632         return true;
1633     }
1634
1635     let mut autoderef =
1636         Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty, span);
1637
1638     // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1639     if arbitrary_self_types_enabled {
1640         autoderef = autoderef.include_raw_pointers();
1641     }
1642
1643     // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1644     autoderef.next();
1645
1646     let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, None);
1647
1648     // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1649     loop {
1650         if let Some((potential_self_ty, _)) = autoderef.next() {
1651             debug!(
1652                 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1653                 potential_self_ty, self_ty
1654             );
1655
1656             if can_eq_self(potential_self_ty) {
1657                 wfcx.register_obligations(autoderef.into_obligations());
1658
1659                 if let Err(err) =
1660                     wfcx.equate_types(&cause, wfcx.param_env, self_ty, potential_self_ty)
1661                 {
1662                     infcx.report_mismatched_types(&cause, self_ty, potential_self_ty, err).emit();
1663                 }
1664
1665                 break;
1666             } else {
1667                 // Without `feature(arbitrary_self_types)`, we require that each step in the
1668                 // deref chain implement `receiver`
1669                 if !arbitrary_self_types_enabled
1670                     && !receiver_is_implemented(
1671                         wfcx,
1672                         receiver_trait_def_id,
1673                         cause.clone(),
1674                         potential_self_ty,
1675                     )
1676                 {
1677                     return false;
1678                 }
1679             }
1680         } else {
1681             debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1682             // If the receiver already has errors reported due to it, consider it valid to avoid
1683             // unnecessary errors (#58712).
1684             return receiver_ty.references_error();
1685         }
1686     }
1687
1688     // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1689     if !arbitrary_self_types_enabled
1690         && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1691     {
1692         return false;
1693     }
1694
1695     true
1696 }
1697
1698 fn receiver_is_implemented<'tcx>(
1699     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1700     receiver_trait_def_id: DefId,
1701     cause: ObligationCause<'tcx>,
1702     receiver_ty: Ty<'tcx>,
1703 ) -> bool {
1704     let tcx = wfcx.tcx();
1705     let trait_ref = ty::Binder::dummy(ty::TraitRef {
1706         def_id: receiver_trait_def_id,
1707         substs: tcx.mk_substs_trait(receiver_ty, &[]),
1708     });
1709
1710     let obligation =
1711         traits::Obligation::new(cause, wfcx.param_env, trait_ref.without_const().to_predicate(tcx));
1712
1713     if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1714         true
1715     } else {
1716         debug!(
1717             "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1718             receiver_ty
1719         );
1720         false
1721     }
1722 }
1723
1724 fn check_variances_for_type_defn<'tcx>(
1725     tcx: TyCtxt<'tcx>,
1726     item: &hir::Item<'tcx>,
1727     hir_generics: &hir::Generics<'_>,
1728 ) {
1729     let ty = tcx.type_of(item.def_id);
1730     if tcx.has_error_field(ty) {
1731         return;
1732     }
1733
1734     let ty_predicates = tcx.predicates_of(item.def_id);
1735     assert_eq!(ty_predicates.parent, None);
1736     let variances = tcx.variances_of(item.def_id);
1737
1738     let mut constrained_parameters: FxHashSet<_> = variances
1739         .iter()
1740         .enumerate()
1741         .filter(|&(_, &variance)| variance != ty::Bivariant)
1742         .map(|(index, _)| Parameter(index as u32))
1743         .collect();
1744
1745     identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1746
1747     // Lazily calculated because it is only needed in case of an error.
1748     let explicitly_bounded_params = LazyCell::new(|| {
1749         let icx = crate::collect::ItemCtxt::new(tcx, item.def_id.to_def_id());
1750         hir_generics
1751             .predicates
1752             .iter()
1753             .filter_map(|predicate| match predicate {
1754                 hir::WherePredicate::BoundPredicate(predicate) => {
1755                     match icx.to_ty(predicate.bounded_ty).kind() {
1756                         ty::Param(data) => Some(Parameter(data.index)),
1757                         _ => None,
1758                     }
1759                 }
1760                 _ => None,
1761             })
1762             .collect::<FxHashSet<_>>()
1763     });
1764
1765     for (index, _) in variances.iter().enumerate() {
1766         let parameter = Parameter(index as u32);
1767
1768         if constrained_parameters.contains(&parameter) {
1769             continue;
1770         }
1771
1772         let param = &hir_generics.params[index];
1773
1774         match param.name {
1775             hir::ParamName::Error => {}
1776             _ => {
1777                 let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
1778                 report_bivariance(tcx, param, has_explicit_bounds);
1779             }
1780         }
1781     }
1782 }
1783
1784 fn report_bivariance(
1785     tcx: TyCtxt<'_>,
1786     param: &rustc_hir::GenericParam<'_>,
1787     has_explicit_bounds: bool,
1788 ) -> ErrorGuaranteed {
1789     let span = param.span;
1790     let param_name = param.name.ident().name;
1791     let mut err = error_392(tcx, span, param_name);
1792
1793     let suggested_marker_id = tcx.lang_items().phantom_data();
1794     // Help is available only in presence of lang items.
1795     let msg = if let Some(def_id) = suggested_marker_id {
1796         format!(
1797             "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1798             param_name,
1799             tcx.def_path_str(def_id),
1800         )
1801     } else {
1802         format!("consider removing `{param_name}` or referring to it in a field")
1803     };
1804     err.help(&msg);
1805
1806     if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
1807         err.help(&format!(
1808             "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1809             param_name
1810         ));
1811     }
1812     err.emit()
1813 }
1814
1815 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
1816     /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1817     /// aren't true.
1818     fn check_false_global_bounds(&mut self) {
1819         let tcx = self.ocx.infcx.tcx;
1820         let mut span = self.span;
1821         let empty_env = ty::ParamEnv::empty();
1822
1823         let def_id = tcx.hir().local_def_id(self.body_id);
1824         let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied();
1825         // Check elaborated bounds.
1826         let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
1827
1828         for obligation in implied_obligations {
1829             // We lower empty bounds like `Vec<dyn Copy>:` as
1830             // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
1831             // regular WF checking
1832             if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
1833                 continue;
1834             }
1835             let pred = obligation.predicate;
1836             // Match the existing behavior.
1837             if pred.is_global() && !pred.has_late_bound_regions() {
1838                 let pred = self.normalize(span, None, pred);
1839                 let hir_node = tcx.hir().find(self.body_id);
1840
1841                 // only use the span of the predicate clause (#90869)
1842
1843                 if let Some(hir::Generics { predicates, .. }) =
1844                     hir_node.and_then(|node| node.generics())
1845                 {
1846                     let obligation_span = obligation.cause.span();
1847
1848                     span = predicates
1849                         .iter()
1850                         // There seems to be no better way to find out which predicate we are in
1851                         .find(|pred| pred.span().contains(obligation_span))
1852                         .map(|pred| pred.span())
1853                         .unwrap_or(obligation_span);
1854                 }
1855
1856                 let obligation = traits::Obligation::new(
1857                     traits::ObligationCause::new(span, self.body_id, traits::TrivialBound),
1858                     empty_env,
1859                     pred,
1860                 );
1861                 self.ocx.register_obligation(obligation);
1862             }
1863         }
1864     }
1865 }
1866
1867 fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
1868     let items = tcx.hir_module_items(module);
1869     items.par_items(|item| tcx.ensure().check_well_formed(item.def_id));
1870     items.par_impl_items(|item| tcx.ensure().check_well_formed(item.def_id));
1871     items.par_trait_items(|item| tcx.ensure().check_well_formed(item.def_id));
1872     items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.def_id));
1873 }
1874
1875 ///////////////////////////////////////////////////////////////////////////
1876 // ADT
1877
1878 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1879 struct AdtVariant<'tcx> {
1880     /// Types of fields in the variant, that must be well-formed.
1881     fields: Vec<AdtField<'tcx>>,
1882
1883     /// Explicit discriminant of this variant (e.g. `A = 123`),
1884     /// that must evaluate to a constant value.
1885     explicit_discr: Option<LocalDefId>,
1886 }
1887
1888 struct AdtField<'tcx> {
1889     ty: Ty<'tcx>,
1890     def_id: LocalDefId,
1891     span: Span,
1892 }
1893
1894 impl<'a, 'tcx> WfCheckingCtxt<'a, 'tcx> {
1895     // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1896     fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1897         let fields = struct_def
1898             .fields()
1899             .iter()
1900             .map(|field| {
1901                 let def_id = self.tcx().hir().local_def_id(field.hir_id);
1902                 let field_ty = self.tcx().type_of(def_id);
1903                 let field_ty = self.normalize(field.ty.span, None, field_ty);
1904                 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1905                 AdtField { ty: field_ty, span: field.ty.span, def_id }
1906             })
1907             .collect();
1908         AdtVariant { fields, explicit_discr: None }
1909     }
1910
1911     fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1912         enum_def
1913             .variants
1914             .iter()
1915             .map(|variant| AdtVariant {
1916                 fields: self.non_enum_variant(&variant.data).fields,
1917                 explicit_discr: variant
1918                     .disr_expr
1919                     .map(|explicit_discr| self.tcx().hir().local_def_id(explicit_discr.hir_id)),
1920             })
1921             .collect()
1922     }
1923 }
1924
1925 pub fn impl_implied_bounds<'tcx>(
1926     tcx: TyCtxt<'tcx>,
1927     param_env: ty::ParamEnv<'tcx>,
1928     impl_def_id: LocalDefId,
1929     span: Span,
1930 ) -> FxHashSet<Ty<'tcx>> {
1931     // We completely ignore any obligations caused by normalizing the types
1932     // we assume to be well formed. Considering that the user of the implied
1933     // bounds will also normalize them, we leave it to them to emit errors
1934     // which should result in better causes and spans.
1935     tcx.infer_ctxt().enter(|infcx| {
1936         let cause = ObligationCause::misc(span, tcx.hir().local_def_id_to_hir_id(impl_def_id));
1937         match tcx.impl_trait_ref(impl_def_id) {
1938             Some(trait_ref) => {
1939                 // Trait impl: take implied bounds from all types that
1940                 // appear in the trait reference.
1941                 match infcx.at(&cause, param_env).normalize(trait_ref) {
1942                     Ok(Normalized { value, obligations: _ }) => value.substs.types().collect(),
1943                     Err(NoSolution) => FxHashSet::default(),
1944                 }
1945             }
1946
1947             None => {
1948                 // Inherent impl: take implied bounds from the `self` type.
1949                 let self_ty = tcx.type_of(impl_def_id);
1950                 match infcx.at(&cause, param_env).normalize(self_ty) {
1951                     Ok(Normalized { value, obligations: _ }) => FxHashSet::from_iter([value]),
1952                     Err(NoSolution) => FxHashSet::default(),
1953                 }
1954             }
1955         }
1956     })
1957 }
1958
1959 fn error_392(
1960     tcx: TyCtxt<'_>,
1961     span: Span,
1962     param_name: Symbol,
1963 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
1964     let mut err = struct_span_err!(tcx.sess, span, E0392, "parameter `{param_name}` is never used");
1965     err.span_label(span, "unused parameter");
1966     err
1967 }
1968
1969 pub fn provide(providers: &mut Providers) {
1970     *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };
1971 }