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