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