]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/wfcheck.rs
2ac183b504e0560d012fcfe44836d3f2c2be54a9
[rust.git] / compiler / rustc_typeck / src / check / wfcheck.rs
1 use crate::check::regionck::OutlivesEnvironmentExt;
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
3 use rustc_ast as ast;
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
6 use rustc_hir as hir;
7 use rustc_hir::def_id::{DefId, LocalDefId};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir::ItemKind;
10 use rustc_infer::infer::outlives::env::{OutlivesEnvironment, 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::query::evaluate_obligation::InferCtxtExt as _;
26 use rustc_trait_selection::traits::{
27     self, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc,
28 };
29
30 use std::cell::LazyCell;
31 use std::convert::TryInto;
32 use std::iter;
33 use std::ops::{ControlFlow, Deref};
34
35 pub(super) struct WfCheckingCtxt<'a, 'tcx> {
36     pub(super) ocx: ObligationCtxt<'a, 'tcx>,
37     span: Span,
38     body_id: hir::HirId,
39     param_env: ty::ParamEnv<'tcx>,
40 }
41 impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
42     type Target = ObligationCtxt<'a, 'tcx>;
43     fn deref(&self) -> &Self::Target {
44         &self.ocx
45     }
46 }
47
48 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
49     fn tcx(&self) -> TyCtxt<'tcx> {
50         self.ocx.infcx.tcx
51     }
52
53     fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
54     where
55         T: TypeFoldable<'tcx>,
56     {
57         self.ocx.normalize(
58             ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc)),
59             self.param_env,
60             value,
61         )
62     }
63
64     fn register_wf_obligation(
65         &self,
66         span: Span,
67         loc: Option<WellFormedLoc>,
68         arg: ty::GenericArg<'tcx>,
69     ) {
70         let cause =
71             traits::ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc));
72         self.ocx.register_obligation(traits::Obligation::new(
73             cause,
74             self.param_env,
75             ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx()),
76         ));
77     }
78 }
79
80 pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
81     tcx: TyCtxt<'tcx>,
82     span: Span,
83     body_def_id: LocalDefId,
84     f: F,
85 ) where
86     F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>),
87 {
88     let param_env = tcx.param_env(body_def_id);
89     let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id);
90     tcx.infer_ctxt().enter(|ref infcx| {
91         let ocx = ObligationCtxt::new(infcx);
92
93         let assumed_wf_types = tcx.assumed_wf_types(body_def_id);
94         let mut implied_bounds = FxHashSet::default();
95         let cause = ObligationCause::misc(span, body_id);
96         for ty in assumed_wf_types {
97             implied_bounds.insert(ty);
98             let normalized = ocx.normalize(cause.clone(), param_env, ty);
99             implied_bounds.insert(normalized);
100         }
101         let implied_bounds = implied_bounds;
102
103         let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env };
104
105         if !tcx.features().trivial_bounds {
106             wfcx.check_false_global_bounds()
107         }
108         f(&mut wfcx);
109         let errors = wfcx.select_all_or_error();
110         if !errors.is_empty() {
111             infcx.report_fulfillment_errors(&errors, None, false);
112             return;
113         }
114
115         let mut outlives_environment = OutlivesEnvironment::new(param_env);
116         outlives_environment.add_implied_bounds(infcx, implied_bounds, body_id);
117         infcx.check_region_obligations_and_report_errors(body_def_id, &outlives_environment);
118     })
119 }
120
121 fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
122     let node = tcx.hir().expect_owner(def_id);
123     match node {
124         hir::OwnerNode::Crate(_) => {}
125         hir::OwnerNode::Item(item) => check_item(tcx, item),
126         hir::OwnerNode::TraitItem(item) => check_trait_item(tcx, item),
127         hir::OwnerNode::ImplItem(item) => check_impl_item(tcx, item),
128         hir::OwnerNode::ForeignItem(item) => check_foreign_item(tcx, item),
129     }
130
131     if let Some(generics) = node.generics() {
132         for param in generics.params {
133             check_param_wf(tcx, param)
134         }
135     }
136 }
137
138 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
139 /// well-formed, meaning that they do not require any constraints not declared in the struct
140 /// definition itself. For example, this definition would be illegal:
141 ///
142 /// ```rust
143 /// struct Ref<'a, T> { x: &'a T }
144 /// ```
145 ///
146 /// because the type did not declare that `T:'a`.
147 ///
148 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
149 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
150 /// the types first.
151 #[instrument(skip(tcx), level = "debug")]
152 fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
153     let def_id = item.def_id;
154
155     debug!(
156         ?item.def_id,
157         item.name = ? tcx.def_path_str(def_id.to_def_id())
158     );
159
160     match item.kind {
161         // Right now we check that every default trait implementation
162         // has an implementation of itself. Basically, a case like:
163         //
164         //     impl Trait for T {}
165         //
166         // has a requirement of `T: Trait` which was required for default
167         // method implementations. Although this could be improved now that
168         // there's a better infrastructure in place for this, it's being left
169         // for a follow-up work.
170         //
171         // Since there's such a requirement, we need to check *just* positive
172         // implementations, otherwise things like:
173         //
174         //     impl !Send for T {}
175         //
176         // won't be allowed unless there's an *explicit* implementation of `Send`
177         // for `T`
178         hir::ItemKind::Impl(ref impl_) => {
179             let is_auto = tcx
180                 .impl_trait_ref(item.def_id)
181                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
182             if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
183                 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
184                 let mut err =
185                     tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
186                 err.span_labels(impl_.defaultness_span, "default because of this");
187                 err.span_label(sp, "auto trait");
188                 err.emit();
189             }
190             // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
191             match (tcx.impl_polarity(def_id), impl_.polarity) {
192                 (ty::ImplPolarity::Positive, _) => {
193                     check_impl(tcx, item, impl_.self_ty, &impl_.of_trait, impl_.constness);
194                 }
195                 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
196                     // FIXME(#27579): what amount of WF checking do we need for neg impls?
197                     if let hir::Defaultness::Default { .. } = impl_.defaultness {
198                         let mut spans = vec![span];
199                         spans.extend(impl_.defaultness_span);
200                         struct_span_err!(
201                             tcx.sess,
202                             spans,
203                             E0750,
204                             "negative impls cannot be default impls"
205                         )
206                         .emit();
207                     }
208                 }
209                 (ty::ImplPolarity::Reservation, _) => {
210                     // FIXME: what amount of WF checking do we need for reservation impls?
211                 }
212                 _ => unreachable!(),
213             }
214         }
215         hir::ItemKind::Fn(ref sig, ..) => {
216             check_item_fn(tcx, item.def_id, item.ident, item.span, sig.decl);
217         }
218         hir::ItemKind::Static(ty, ..) => {
219             check_item_type(tcx, item.def_id, ty.span, false);
220         }
221         hir::ItemKind::Const(ty, ..) => {
222             check_item_type(tcx, item.def_id, ty.span, false);
223         }
224         hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
225             check_type_defn(tcx, item, false, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
226
227             check_variances_for_type_defn(tcx, item, ast_generics);
228         }
229         hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
230             check_type_defn(tcx, item, true, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
231
232             check_variances_for_type_defn(tcx, item, ast_generics);
233         }
234         hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
235             check_type_defn(tcx, item, true, |wfcx| wfcx.enum_variants(enum_def));
236
237             check_variances_for_type_defn(tcx, item, ast_generics);
238         }
239         hir::ItemKind::Trait(..) => {
240             check_trait(tcx, item);
241         }
242         hir::ItemKind::TraitAlias(..) => {
243             check_trait(tcx, item);
244         }
245         // `ForeignItem`s are handled separately.
246         hir::ItemKind::ForeignMod { .. } => {}
247         _ => {}
248     }
249 }
250
251 fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) {
252     let def_id = item.def_id;
253
254     debug!(
255         ?item.def_id,
256         item.name = ? tcx.def_path_str(def_id.to_def_id())
257     );
258
259     match item.kind {
260         hir::ForeignItemKind::Fn(decl, ..) => {
261             check_item_fn(tcx, item.def_id, item.ident, item.span, decl)
262         }
263         hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, item.def_id, ty.span, true),
264         hir::ForeignItemKind::Type => (),
265     }
266 }
267
268 fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) {
269     let def_id = trait_item.def_id;
270
271     let (method_sig, span) = match trait_item.kind {
272         hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
273         hir::TraitItemKind::Type(_bounds, Some(ty)) => (None, ty.span),
274         _ => (None, trait_item.span),
275     };
276     check_object_unsafe_self_trait_by_name(tcx, trait_item);
277     check_associated_item(tcx, trait_item.def_id, span, method_sig);
278
279     let encl_trait_def_id = tcx.local_parent(def_id);
280     let encl_trait = tcx.hir().expect_item(encl_trait_def_id);
281     let encl_trait_def_id = encl_trait.def_id.to_def_id();
282     let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
283         Some("fn")
284     } else if Some(encl_trait_def_id) == tcx.lang_items().fn_mut_trait() {
285         Some("fn_mut")
286     } else {
287         None
288     };
289
290     if let (Some(fn_lang_item_name), "call") =
291         (fn_lang_item_name, trait_item.ident.name.to_ident_string().as_str())
292     {
293         // We are looking at the `call` function of the `fn` or `fn_mut` lang item.
294         // Do some rudimentary sanity checking to avoid an ICE later (issue #83471).
295         if let Some(hir::FnSig { decl, span, .. }) = method_sig {
296             if let [self_ty, _] = decl.inputs {
297                 if !matches!(self_ty.kind, hir::TyKind::Rptr(_, _)) {
298                     tcx.sess
299                         .struct_span_err(
300                             self_ty.span,
301                             &format!(
302                                 "first argument of `call` in `{fn_lang_item_name}` lang item must be a reference",
303                             ),
304                         )
305                         .emit();
306                 }
307             } else {
308                 tcx.sess
309                     .struct_span_err(
310                         *span,
311                         &format!(
312                             "`call` function in `{fn_lang_item_name}` lang item takes exactly two arguments",
313                         ),
314                     )
315                     .emit();
316             }
317         } else {
318             tcx.sess
319                 .struct_span_err(
320                     trait_item.span,
321                     &format!(
322                         "`call` trait item in `{fn_lang_item_name}` lang item must be a function",
323                     ),
324                 )
325                 .emit();
326         }
327     }
328 }
329
330 /// Require that the user writes where clauses on GATs for the implicit
331 /// outlives bounds involving trait parameters in trait functions and
332 /// lifetimes passed as GAT substs. See `self-outlives-lint` test.
333 ///
334 /// We use the following trait as an example throughout this function:
335 /// ```rust,ignore (this code fails due to this lint)
336 /// trait IntoIter {
337 ///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
338 ///     type Item<'a>;
339 ///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
340 /// }
341 /// ```
342 fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRef]) {
343     // Associates every GAT's def_id to a list of possibly missing bounds detected by this lint.
344     let mut required_bounds_by_item = FxHashMap::default();
345
346     // Loop over all GATs together, because if this lint suggests adding a where-clause bound
347     // to one GAT, it might then require us to an additional bound on another GAT.
348     // In our `IntoIter` example, we discover a missing `Self: 'a` bound on `Iter<'a>`, which
349     // then in a second loop adds a `Self: 'a` bound to `Item` due to the relationship between
350     // those GATs.
351     loop {
352         let mut should_continue = false;
353         for gat_item in associated_items {
354             let gat_def_id = gat_item.id.def_id;
355             let gat_item = tcx.associated_item(gat_def_id);
356             // If this item is not an assoc ty, or has no substs, then it's not a GAT
357             if gat_item.kind != ty::AssocKind::Type {
358                 continue;
359             }
360             let gat_generics = tcx.generics_of(gat_def_id);
361             // FIXME(jackh726): we can also warn in the more general case
362             if gat_generics.params.is_empty() {
363                 continue;
364             }
365
366             // Gather the bounds with which all other items inside of this trait constrain the GAT.
367             // This is calculated by taking the intersection of the bounds that each item
368             // constrains the GAT with individually.
369             let mut new_required_bounds: Option<FxHashSet<ty::Predicate<'_>>> = None;
370             for item in associated_items {
371                 let item_def_id = item.id.def_id;
372                 // Skip our own GAT, since it does not constrain itself at all.
373                 if item_def_id == gat_def_id {
374                     continue;
375                 }
376
377                 let item_hir_id = item.id.hir_id();
378                 let param_env = tcx.param_env(item_def_id);
379
380                 let item_required_bounds = match item.kind {
381                     // In our example, this corresponds to `into_iter` method
382                     hir::AssocItemKind::Fn { .. } => {
383                         // For methods, we check the function signature's return type for any GATs
384                         // to constrain. In the `into_iter` case, we see that the return type
385                         // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from.
386                         let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions(
387                             item_def_id.to_def_id(),
388                             tcx.fn_sig(item_def_id),
389                         );
390                         gather_gat_bounds(
391                             tcx,
392                             param_env,
393                             item_hir_id,
394                             sig.output(),
395                             // We also assume that all of the function signature's parameter types
396                             // are well formed.
397                             &sig.inputs().iter().copied().collect(),
398                             gat_def_id,
399                             gat_generics,
400                         )
401                     }
402                     // In our example, this corresponds to the `Iter` and `Item` associated types
403                     hir::AssocItemKind::Type => {
404                         // If our associated item is a GAT with missing bounds, add them to
405                         // the param-env here. This allows this GAT to propagate missing bounds
406                         // to other GATs.
407                         let param_env = augment_param_env(
408                             tcx,
409                             param_env,
410                             required_bounds_by_item.get(&item_def_id),
411                         );
412                         gather_gat_bounds(
413                             tcx,
414                             param_env,
415                             item_hir_id,
416                             tcx.explicit_item_bounds(item_def_id)
417                                 .iter()
418                                 .copied()
419                                 .collect::<Vec<_>>(),
420                             &FxHashSet::default(),
421                             gat_def_id,
422                             gat_generics,
423                         )
424                     }
425                     hir::AssocItemKind::Const => None,
426                 };
427
428                 if let Some(item_required_bounds) = item_required_bounds {
429                     // Take the intersection of the required bounds for this GAT, and
430                     // the item_required_bounds which are the ones implied by just
431                     // this item alone.
432                     // This is why we use an Option<_>, since we need to distinguish
433                     // the empty set of bounds from the _uninitialized_ set of bounds.
434                     if let Some(new_required_bounds) = &mut new_required_bounds {
435                         new_required_bounds.retain(|b| item_required_bounds.contains(b));
436                     } else {
437                         new_required_bounds = Some(item_required_bounds);
438                     }
439                 }
440             }
441
442             if let Some(new_required_bounds) = new_required_bounds {
443                 let required_bounds = required_bounds_by_item.entry(gat_def_id).or_default();
444                 if new_required_bounds.into_iter().any(|p| required_bounds.insert(p)) {
445                     // Iterate until our required_bounds no longer change
446                     // Since they changed here, we should continue the loop
447                     should_continue = true;
448                 }
449             }
450         }
451         // We know that this loop will eventually halt, since we only set `should_continue` if the
452         // `required_bounds` for this item grows. Since we are not creating any new region or type
453         // variables, the set of all region and type bounds that we could ever insert are limited
454         // by the number of unique types and regions we observe in a given item.
455         if !should_continue {
456             break;
457         }
458     }
459
460     for (gat_def_id, required_bounds) in required_bounds_by_item {
461         let gat_item_hir = tcx.hir().expect_trait_item(gat_def_id);
462         debug!(?required_bounds);
463         let param_env = tcx.param_env(gat_def_id);
464         let gat_hir = gat_item_hir.hir_id();
465
466         let mut unsatisfied_bounds: Vec<_> = required_bounds
467             .into_iter()
468             .filter(|clause| match clause.kind().skip_binder() {
469                 ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => {
470                     !region_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
471                 }
472                 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
473                     !ty_known_to_outlive(tcx, gat_hir, param_env, &FxHashSet::default(), a, b)
474                 }
475                 _ => bug!("Unexpected PredicateKind"),
476             })
477             .map(|clause| clause.to_string())
478             .collect();
479
480         // We sort so that order is predictable
481         unsatisfied_bounds.sort();
482
483         if !unsatisfied_bounds.is_empty() {
484             let plural = pluralize!(unsatisfied_bounds.len());
485             let mut err = tcx.sess.struct_span_err(
486                 gat_item_hir.span,
487                 &format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
488             );
489
490             let suggestion = format!(
491                 "{} {}",
492                 gat_item_hir.generics.add_where_or_trailing_comma(),
493                 unsatisfied_bounds.join(", "),
494             );
495             err.span_suggestion(
496                 gat_item_hir.generics.tail_span_for_predicate_suggestion(),
497                 &format!("add the required where clause{plural}"),
498                 suggestion,
499                 Applicability::MachineApplicable,
500             );
501
502             let bound =
503                 if unsatisfied_bounds.len() > 1 { "these bounds are" } else { "this bound is" };
504             err.note(&format!(
505                 "{} currently required to ensure that impls have maximum flexibility",
506                 bound
507             ));
508             err.note(
509                 "we are soliciting feedback, see issue #87479 \
510                  <https://github.com/rust-lang/rust/issues/87479> \
511                  for more information",
512             );
513
514             err.emit();
515         }
516     }
517 }
518
519 /// Add a new set of predicates to the caller_bounds of an existing param_env.
520 fn augment_param_env<'tcx>(
521     tcx: TyCtxt<'tcx>,
522     param_env: ty::ParamEnv<'tcx>,
523     new_predicates: Option<&FxHashSet<ty::Predicate<'tcx>>>,
524 ) -> ty::ParamEnv<'tcx> {
525     let Some(new_predicates) = new_predicates else {
526         return param_env;
527     };
528
529     if new_predicates.is_empty() {
530         return param_env;
531     }
532
533     let bounds =
534         tcx.mk_predicates(param_env.caller_bounds().iter().chain(new_predicates.iter().cloned()));
535     // FIXME(compiler-errors): Perhaps there is a case where we need to normalize this
536     // i.e. traits::normalize_param_env_or_error
537     ty::ParamEnv::new(bounds, param_env.reveal(), param_env.constness())
538 }
539
540 /// We use the following trait as an example throughout this function.
541 /// Specifically, let's assume that `to_check` here is the return type
542 /// of `into_iter`, and the GAT we are checking this for is `Iter`.
543 /// ```rust,ignore (this code fails due to this lint)
544 /// trait IntoIter {
545 ///     type Iter<'a>: Iterator<Item = Self::Item<'a>>;
546 ///     type Item<'a>;
547 ///     fn into_iter<'a>(&'a self) -> Self::Iter<'a>;
548 /// }
549 /// ```
550 fn gather_gat_bounds<'tcx, T: TypeFoldable<'tcx>>(
551     tcx: TyCtxt<'tcx>,
552     param_env: ty::ParamEnv<'tcx>,
553     item_hir: hir::HirId,
554     to_check: T,
555     wf_tys: &FxHashSet<Ty<'tcx>>,
556     gat_def_id: LocalDefId,
557     gat_generics: &'tcx ty::Generics,
558 ) -> Option<FxHashSet<ty::Predicate<'tcx>>> {
559     // The bounds we that we would require from `to_check`
560     let mut bounds = FxHashSet::default();
561
562     let (regions, types) = GATSubstCollector::visit(gat_def_id.to_def_id(), to_check);
563
564     // If both regions and types are empty, then this GAT isn't in the
565     // set of types we are checking, and we shouldn't try to do clause analysis
566     // (particularly, doing so would end up with an empty set of clauses,
567     // since the current method would require none, and we take the
568     // intersection of requirements of all methods)
569     if types.is_empty() && regions.is_empty() {
570         return None;
571     }
572
573     for (region_a, region_a_idx) in &regions {
574         // Ignore `'static` lifetimes for the purpose of this lint: it's
575         // because we know it outlives everything and so doesn't give meaningful
576         // clues
577         if let ty::ReStatic = **region_a {
578             continue;
579         }
580         // For each region argument (e.g., `'a` in our example), check for a
581         // relationship to the type arguments (e.g., `Self`). If there is an
582         // outlives relationship (`Self: 'a`), then we want to ensure that is
583         // reflected in a where clause on the GAT itself.
584         for (ty, ty_idx) in &types {
585             // In our example, requires that `Self: 'a`
586             if ty_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *ty, *region_a) {
587                 debug!(?ty_idx, ?region_a_idx);
588                 debug!("required clause: {ty} must outlive {region_a}");
589                 // Translate into the generic parameters of the GAT. In
590                 // our example, the type was `Self`, which will also be
591                 // `Self` in the GAT.
592                 let ty_param = gat_generics.param_at(*ty_idx, tcx);
593                 let ty_param = tcx
594                     .mk_ty(ty::Param(ty::ParamTy { index: ty_param.index, name: ty_param.name }));
595                 // Same for the region. In our example, 'a corresponds
596                 // to the 'me parameter.
597                 let region_param = gat_generics.param_at(*region_a_idx, tcx);
598                 let region_param =
599                     tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
600                         def_id: region_param.def_id,
601                         index: region_param.index,
602                         name: region_param.name,
603                     }));
604                 // The predicate we expect to see. (In our example,
605                 // `Self: 'me`.)
606                 let clause =
607                     ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_param, region_param));
608                 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
609                 bounds.insert(clause);
610             }
611         }
612
613         // For each region argument (e.g., `'a` in our example), also check for a
614         // relationship to the other region arguments. If there is an outlives
615         // relationship, then we want to ensure that is reflected in the where clause
616         // on the GAT itself.
617         for (region_b, region_b_idx) in &regions {
618             // Again, skip `'static` because it outlives everything. Also, we trivially
619             // know that a region outlives itself.
620             if ty::ReStatic == **region_b || region_a == region_b {
621                 continue;
622             }
623             if region_known_to_outlive(tcx, item_hir, param_env, &wf_tys, *region_a, *region_b) {
624                 debug!(?region_a_idx, ?region_b_idx);
625                 debug!("required clause: {region_a} must outlive {region_b}");
626                 // Translate into the generic parameters of the GAT.
627                 let region_a_param = gat_generics.param_at(*region_a_idx, tcx);
628                 let region_a_param =
629                     tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
630                         def_id: region_a_param.def_id,
631                         index: region_a_param.index,
632                         name: region_a_param.name,
633                     }));
634                 // Same for the region.
635                 let region_b_param = gat_generics.param_at(*region_b_idx, tcx);
636                 let region_b_param =
637                     tcx.mk_region(ty::RegionKind::ReEarlyBound(ty::EarlyBoundRegion {
638                         def_id: region_b_param.def_id,
639                         index: region_b_param.index,
640                         name: region_b_param.name,
641                     }));
642                 // The predicate we expect to see.
643                 let clause = ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(
644                     region_a_param,
645                     region_b_param,
646                 ));
647                 let clause = tcx.mk_predicate(ty::Binder::dummy(clause));
648                 bounds.insert(clause);
649             }
650         }
651     }
652
653     Some(bounds)
654 }
655
656 /// Given a known `param_env` and a set of well formed types, can we prove that
657 /// `ty` outlives `region`.
658 fn ty_known_to_outlive<'tcx>(
659     tcx: TyCtxt<'tcx>,
660     id: hir::HirId,
661     param_env: ty::ParamEnv<'tcx>,
662     wf_tys: &FxHashSet<Ty<'tcx>>,
663     ty: Ty<'tcx>,
664     region: ty::Region<'tcx>,
665 ) -> bool {
666     resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| {
667         let origin = infer::RelateParamBound(DUMMY_SP, ty, None);
668         let outlives = &mut TypeOutlives::new(infcx, tcx, region_bound_pairs, None, param_env);
669         outlives.type_must_outlive(origin, ty, region);
670     })
671 }
672
673 /// Given a known `param_env` and a set of well formed types, can we prove that
674 /// `region_a` outlives `region_b`
675 fn region_known_to_outlive<'tcx>(
676     tcx: TyCtxt<'tcx>,
677     id: hir::HirId,
678     param_env: ty::ParamEnv<'tcx>,
679     wf_tys: &FxHashSet<Ty<'tcx>>,
680     region_a: ty::Region<'tcx>,
681     region_b: ty::Region<'tcx>,
682 ) -> bool {
683     resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |mut infcx, _| {
684         use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
685         let origin = infer::RelateRegionParamBound(DUMMY_SP);
686         // `region_a: region_b` -> `region_b <= region_a`
687         infcx.push_sub_region_constraint(origin, region_b, region_a);
688     })
689 }
690
691 /// Given a known `param_env` and a set of well formed types, set up an
692 /// `InferCtxt`, call the passed function (to e.g. set up region constraints
693 /// to be tested), then resolve region and return errors
694 fn resolve_regions_with_wf_tys<'tcx>(
695     tcx: TyCtxt<'tcx>,
696     id: hir::HirId,
697     param_env: ty::ParamEnv<'tcx>,
698     wf_tys: &FxHashSet<Ty<'tcx>>,
699     add_constraints: impl for<'a> FnOnce(&'a InferCtxt<'a, 'tcx>, &'a RegionBoundPairs<'tcx>),
700 ) -> bool {
701     // Unfortunately, we have to use a new `InferCtxt` each call, because
702     // region constraints get added and solved there and we need to test each
703     // call individually.
704     tcx.infer_ctxt().enter(|infcx| {
705         let mut outlives_environment = OutlivesEnvironment::new(param_env);
706         outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id);
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.and_then(|r| r.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 #[tracing::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 #[tracing::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(item.span, None, self_ty);
1267                 wfcx.register_wf_obligation(
1268                     ast_self_ty.span,
1269                     Some(WellFormedLoc::Ty(item.hir_id().expect_owner())),
1270                     self_ty.into(),
1271                 );
1272             }
1273         }
1274
1275         check_where_clauses(wfcx, item.span, item.def_id);
1276     });
1277 }
1278
1279 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1280 #[instrument(level = "debug", skip(wfcx))]
1281 fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1282     let infcx = wfcx.infcx;
1283     let tcx = wfcx.tcx();
1284
1285     let predicates = tcx.bound_predicates_of(def_id.to_def_id());
1286     let generics = tcx.generics_of(def_id);
1287
1288     let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1289         GenericParamDefKind::Type { has_default, .. }
1290         | GenericParamDefKind::Const { has_default } => {
1291             has_default && def.index >= generics.parent_count as u32
1292         }
1293         GenericParamDefKind::Lifetime => unreachable!(),
1294     };
1295
1296     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1297     // For example, this forbids the declaration:
1298     //
1299     //     struct Foo<T = Vec<[u32]>> { .. }
1300     //
1301     // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1302     for param in &generics.params {
1303         match param.kind {
1304             GenericParamDefKind::Type { .. } => {
1305                 if is_our_default(param) {
1306                     let ty = tcx.type_of(param.def_id);
1307                     // Ignore dependent defaults -- that is, where the default of one type
1308                     // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1309                     // be sure if it will error or not as user might always specify the other.
1310                     if !ty.needs_subst() {
1311                         wfcx.register_wf_obligation(tcx.def_span(param.def_id), None, ty.into());
1312                     }
1313                 }
1314             }
1315             GenericParamDefKind::Const { .. } => {
1316                 if is_our_default(param) {
1317                     // FIXME(const_generics_defaults): This
1318                     // is incorrect when dealing with unused substs, for example
1319                     // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1320                     // we should eagerly error.
1321                     let default_ct = tcx.const_param_default(param.def_id);
1322                     if !default_ct.needs_subst() {
1323                         wfcx.register_wf_obligation(
1324                             tcx.def_span(param.def_id),
1325                             None,
1326                             default_ct.into(),
1327                         );
1328                     }
1329                 }
1330             }
1331             // Doesn't have defaults.
1332             GenericParamDefKind::Lifetime => {}
1333         }
1334     }
1335
1336     // Check that trait predicates are WF when params are substituted by their defaults.
1337     // We don't want to overly constrain the predicates that may be written but we want to
1338     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1339     // Therefore we check if a predicate which contains a single type param
1340     // with a concrete default is WF with that default substituted.
1341     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1342     //
1343     // First we build the defaulted substitution.
1344     let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| {
1345         match param.kind {
1346             GenericParamDefKind::Lifetime => {
1347                 // All regions are identity.
1348                 tcx.mk_param_from_def(param)
1349             }
1350
1351             GenericParamDefKind::Type { .. } => {
1352                 // If the param has a default, ...
1353                 if is_our_default(param) {
1354                     let default_ty = tcx.type_of(param.def_id);
1355                     // ... and it's not a dependent default, ...
1356                     if !default_ty.needs_subst() {
1357                         // ... then substitute it with the default.
1358                         return default_ty.into();
1359                     }
1360                 }
1361
1362                 tcx.mk_param_from_def(param)
1363             }
1364             GenericParamDefKind::Const { .. } => {
1365                 // If the param has a default, ...
1366                 if is_our_default(param) {
1367                     let default_ct = tcx.const_param_default(param.def_id);
1368                     // ... and it's not a dependent default, ...
1369                     if !default_ct.needs_subst() {
1370                         // ... then substitute it with the default.
1371                         return default_ct.into();
1372                     }
1373                 }
1374
1375                 tcx.mk_param_from_def(param)
1376             }
1377         }
1378     });
1379
1380     // Now we build the substituted predicates.
1381     let default_obligations = predicates
1382         .0
1383         .predicates
1384         .iter()
1385         .flat_map(|&(pred, sp)| {
1386             #[derive(Default)]
1387             struct CountParams {
1388                 params: FxHashSet<u32>,
1389             }
1390             impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
1391                 type BreakTy = ();
1392
1393                 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1394                     if let ty::Param(param) = t.kind() {
1395                         self.params.insert(param.index);
1396                     }
1397                     t.super_visit_with(self)
1398                 }
1399
1400                 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1401                     ControlFlow::BREAK
1402                 }
1403
1404                 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1405                     if let ty::ConstKind::Param(param) = c.kind() {
1406                         self.params.insert(param.index);
1407                     }
1408                     c.super_visit_with(self)
1409                 }
1410             }
1411             let mut param_count = CountParams::default();
1412             let has_region = pred.visit_with(&mut param_count).is_break();
1413             let substituted_pred = predicates.rebind(pred).subst(tcx, substs);
1414             // Don't check non-defaulted params, dependent defaults (including lifetimes)
1415             // or preds with multiple params.
1416             if substituted_pred.has_param_types_or_consts()
1417                 || param_count.params.len() > 1
1418                 || has_region
1419             {
1420                 None
1421             } else if predicates.0.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1422                 // Avoid duplication of predicates that contain no parameters, for example.
1423                 None
1424             } else {
1425                 Some((substituted_pred, sp))
1426             }
1427         })
1428         .map(|(pred, sp)| {
1429             // Convert each of those into an obligation. So if you have
1430             // something like `struct Foo<T: Copy = String>`, we would
1431             // take that predicate `T: Copy`, substitute to `String: Copy`
1432             // (actually that happens in the previous `flat_map` call),
1433             // and then try to prove it (in this case, we'll fail).
1434             //
1435             // Note the subtle difference from how we handle `predicates`
1436             // below: there, we are not trying to prove those predicates
1437             // to be *true* but merely *well-formed*.
1438             let pred = wfcx.normalize(sp, None, pred);
1439             let cause = traits::ObligationCause::new(
1440                 sp,
1441                 wfcx.body_id,
1442                 traits::ItemObligation(def_id.to_def_id()),
1443             );
1444             traits::Obligation::new(cause, wfcx.param_env, pred)
1445         });
1446
1447     let predicates = predicates.0.instantiate_identity(tcx);
1448
1449     let predicates = wfcx.normalize(span, None, 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(infcx, wfcx.param_env, wfcx.body_id, p, sp)
1456         });
1457
1458     let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1459     wfcx.register_obligations(obligations);
1460 }
1461
1462 #[tracing::instrument(level = "debug", skip(wfcx, span, hir_decl))]
1463 fn check_fn_or_method<'tcx>(
1464     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1465     span: Span,
1466     sig: ty::PolyFnSig<'tcx>,
1467     hir_decl: &hir::FnDecl<'_>,
1468     def_id: LocalDefId,
1469 ) {
1470     let tcx = wfcx.tcx();
1471     let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1472
1473     // Normalize the input and output types one at a time, using a different
1474     // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1475     // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1476     // for each type, preventing the HIR wf check from generating
1477     // a nice error message.
1478     let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1479     inputs_and_output = tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1480         wfcx.normalize(
1481             span,
1482             Some(WellFormedLoc::Param {
1483                 function: def_id,
1484                 // Note that the `param_idx` of the output type is
1485                 // one greater than the index of the last input type.
1486                 param_idx: i.try_into().unwrap(),
1487             }),
1488             ty,
1489         )
1490     }));
1491     // Manually call `normalize_associated_types_in` on the other types
1492     // in `FnSig`. This ensures that if the types of these fields
1493     // ever change to include projections, we will start normalizing
1494     // them automatically.
1495     let sig = ty::FnSig {
1496         inputs_and_output,
1497         c_variadic: wfcx.normalize(span, None, c_variadic),
1498         unsafety: wfcx.normalize(span, None, unsafety),
1499         abi: wfcx.normalize(span, None, abi),
1500     };
1501
1502     for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1503         wfcx.register_wf_obligation(
1504             ty.span,
1505             Some(WellFormedLoc::Param { function: def_id, param_idx: i.try_into().unwrap() }),
1506             input_ty.into(),
1507         );
1508     }
1509
1510     wfcx.register_wf_obligation(hir_decl.output.span(), None, sig.output().into());
1511
1512     check_where_clauses(wfcx, span, def_id);
1513 }
1514
1515 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1516      `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1517      of the previous types except `Self`)";
1518
1519 #[tracing::instrument(level = "debug", skip(wfcx))]
1520 fn check_method_receiver<'tcx>(
1521     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1522     fn_sig: &hir::FnSig<'_>,
1523     method: &ty::AssocItem,
1524     self_ty: Ty<'tcx>,
1525 ) {
1526     let tcx = wfcx.tcx();
1527
1528     if !method.fn_has_self_parameter {
1529         return;
1530     }
1531
1532     let span = fn_sig.decl.inputs[0].span;
1533
1534     let sig = tcx.fn_sig(method.def_id);
1535     let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1536     let sig = wfcx.normalize(span, None, sig);
1537
1538     debug!("check_method_receiver: sig={:?}", sig);
1539
1540     let self_ty = wfcx.normalize(span, None, self_ty);
1541
1542     let receiver_ty = sig.inputs()[0];
1543     let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1544
1545     if tcx.features().arbitrary_self_types {
1546         if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1547             // Report error; `arbitrary_self_types` was enabled.
1548             e0307(tcx, span, receiver_ty);
1549         }
1550     } else {
1551         if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
1552             if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1553                 // Report error; would have worked with `arbitrary_self_types`.
1554                 feature_err(
1555                     &tcx.sess.parse_sess,
1556                     sym::arbitrary_self_types,
1557                     span,
1558                     &format!(
1559                         "`{receiver_ty}` cannot be used as the type of `self` without \
1560                          the `arbitrary_self_types` feature",
1561                     ),
1562                 )
1563                 .help(HELP_FOR_SELF_TYPE)
1564                 .emit();
1565             } else {
1566                 // Report error; would not have worked with `arbitrary_self_types`.
1567                 e0307(tcx, span, receiver_ty);
1568             }
1569         }
1570     }
1571 }
1572
1573 fn e0307<'tcx>(tcx: TyCtxt<'tcx>, span: Span, receiver_ty: Ty<'_>) {
1574     struct_span_err!(
1575         tcx.sess.diagnostic(),
1576         span,
1577         E0307,
1578         "invalid `self` parameter type: {receiver_ty}"
1579     )
1580     .note("type of `self` must be `Self` or a type that dereferences to it")
1581     .help(HELP_FOR_SELF_TYPE)
1582     .emit();
1583 }
1584
1585 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1586 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1587 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1588 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1589 /// `Deref<Target = self_ty>`.
1590 ///
1591 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1592 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1593 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1594 fn receiver_is_valid<'tcx>(
1595     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1596     span: Span,
1597     receiver_ty: Ty<'tcx>,
1598     self_ty: Ty<'tcx>,
1599     arbitrary_self_types_enabled: bool,
1600 ) -> bool {
1601     let infcx = wfcx.infcx;
1602     let tcx = wfcx.tcx();
1603     let cause =
1604         ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver);
1605
1606     let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
1607
1608     // `self: Self` is always valid.
1609     if can_eq_self(receiver_ty) {
1610         if let Err(err) = wfcx.equate_types(&cause, wfcx.param_env, self_ty, receiver_ty) {
1611             infcx.report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
1612         }
1613         return true;
1614     }
1615
1616     let mut autoderef =
1617         Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty, span);
1618
1619     // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1620     if arbitrary_self_types_enabled {
1621         autoderef = autoderef.include_raw_pointers();
1622     }
1623
1624     // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1625     autoderef.next();
1626
1627     let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, None);
1628
1629     // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1630     loop {
1631         if let Some((potential_self_ty, _)) = autoderef.next() {
1632             debug!(
1633                 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1634                 potential_self_ty, self_ty
1635             );
1636
1637             if can_eq_self(potential_self_ty) {
1638                 wfcx.register_obligations(autoderef.into_obligations());
1639
1640                 if let Err(err) =
1641                     wfcx.equate_types(&cause, wfcx.param_env, self_ty, potential_self_ty)
1642                 {
1643                     infcx.report_mismatched_types(&cause, self_ty, potential_self_ty, err).emit();
1644                 }
1645
1646                 break;
1647             } else {
1648                 // Without `feature(arbitrary_self_types)`, we require that each step in the
1649                 // deref chain implement `receiver`
1650                 if !arbitrary_self_types_enabled
1651                     && !receiver_is_implemented(
1652                         wfcx,
1653                         receiver_trait_def_id,
1654                         cause.clone(),
1655                         potential_self_ty,
1656                     )
1657                 {
1658                     return false;
1659                 }
1660             }
1661         } else {
1662             debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1663             // If the receiver already has errors reported due to it, consider it valid to avoid
1664             // unnecessary errors (#58712).
1665             return receiver_ty.references_error();
1666         }
1667     }
1668
1669     // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1670     if !arbitrary_self_types_enabled
1671         && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1672     {
1673         return false;
1674     }
1675
1676     true
1677 }
1678
1679 fn receiver_is_implemented<'tcx>(
1680     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1681     receiver_trait_def_id: DefId,
1682     cause: ObligationCause<'tcx>,
1683     receiver_ty: Ty<'tcx>,
1684 ) -> bool {
1685     let tcx = wfcx.tcx();
1686     let trait_ref = ty::Binder::dummy(ty::TraitRef {
1687         def_id: receiver_trait_def_id,
1688         substs: tcx.mk_substs_trait(receiver_ty, &[]),
1689     });
1690
1691     let obligation =
1692         traits::Obligation::new(cause, wfcx.param_env, trait_ref.without_const().to_predicate(tcx));
1693
1694     if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1695         true
1696     } else {
1697         debug!(
1698             "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1699             receiver_ty
1700         );
1701         false
1702     }
1703 }
1704
1705 fn check_variances_for_type_defn<'tcx>(
1706     tcx: TyCtxt<'tcx>,
1707     item: &hir::Item<'tcx>,
1708     hir_generics: &hir::Generics<'_>,
1709 ) {
1710     let ty = tcx.type_of(item.def_id);
1711     if tcx.has_error_field(ty) {
1712         return;
1713     }
1714
1715     let ty_predicates = tcx.predicates_of(item.def_id);
1716     assert_eq!(ty_predicates.parent, None);
1717     let variances = tcx.variances_of(item.def_id);
1718
1719     let mut constrained_parameters: FxHashSet<_> = variances
1720         .iter()
1721         .enumerate()
1722         .filter(|&(_, &variance)| variance != ty::Bivariant)
1723         .map(|(index, _)| Parameter(index as u32))
1724         .collect();
1725
1726     identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1727
1728     // Lazily calculated because it is only needed in case of an error.
1729     let explicitly_bounded_params = LazyCell::new(|| {
1730         let icx = crate::collect::ItemCtxt::new(tcx, item.def_id.to_def_id());
1731         hir_generics
1732             .predicates
1733             .iter()
1734             .filter_map(|predicate| match predicate {
1735                 hir::WherePredicate::BoundPredicate(predicate) => {
1736                     match icx.to_ty(predicate.bounded_ty).kind() {
1737                         ty::Param(data) => Some(Parameter(data.index)),
1738                         _ => None,
1739                     }
1740                 }
1741                 _ => None,
1742             })
1743             .collect::<FxHashSet<_>>()
1744     });
1745
1746     for (index, _) in variances.iter().enumerate() {
1747         let parameter = Parameter(index as u32);
1748
1749         if constrained_parameters.contains(&parameter) {
1750             continue;
1751         }
1752
1753         let param = &hir_generics.params[index];
1754
1755         match param.name {
1756             hir::ParamName::Error => {}
1757             _ => {
1758                 let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
1759                 report_bivariance(tcx, param, has_explicit_bounds);
1760             }
1761         }
1762     }
1763 }
1764
1765 fn report_bivariance(
1766     tcx: TyCtxt<'_>,
1767     param: &rustc_hir::GenericParam<'_>,
1768     has_explicit_bounds: bool,
1769 ) -> ErrorGuaranteed {
1770     let span = param.span;
1771     let param_name = param.name.ident().name;
1772     let mut err = error_392(tcx, span, param_name);
1773
1774     let suggested_marker_id = tcx.lang_items().phantom_data();
1775     // Help is available only in presence of lang items.
1776     let msg = if let Some(def_id) = suggested_marker_id {
1777         format!(
1778             "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1779             param_name,
1780             tcx.def_path_str(def_id),
1781         )
1782     } else {
1783         format!("consider removing `{param_name}` or referring to it in a field")
1784     };
1785     err.help(&msg);
1786
1787     if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
1788         err.help(&format!(
1789             "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1790             param_name
1791         ));
1792     }
1793     err.emit()
1794 }
1795
1796 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
1797     /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1798     /// aren't true.
1799     fn check_false_global_bounds(&mut self) {
1800         let tcx = self.ocx.infcx.tcx;
1801         let mut span = self.span;
1802         let empty_env = ty::ParamEnv::empty();
1803
1804         let def_id = tcx.hir().local_def_id(self.body_id);
1805         let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied();
1806         // Check elaborated bounds.
1807         let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
1808
1809         for obligation in implied_obligations {
1810             // We lower empty bounds like `Vec<dyn Copy>:` as
1811             // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
1812             // regular WF checking
1813             if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
1814                 continue;
1815             }
1816             let pred = obligation.predicate;
1817             // Match the existing behavior.
1818             if pred.is_global() && !pred.has_late_bound_regions() {
1819                 let pred = self.normalize(span, None, pred);
1820                 let hir_node = tcx.hir().find(self.body_id);
1821
1822                 // only use the span of the predicate clause (#90869)
1823
1824                 if let Some(hir::Generics { predicates, .. }) =
1825                     hir_node.and_then(|node| node.generics())
1826                 {
1827                     let obligation_span = obligation.cause.span();
1828
1829                     span = predicates
1830                         .iter()
1831                         // There seems to be no better way to find out which predicate we are in
1832                         .find(|pred| pred.span().contains(obligation_span))
1833                         .map(|pred| pred.span())
1834                         .unwrap_or(obligation_span);
1835                 }
1836
1837                 let obligation = traits::Obligation::new(
1838                     traits::ObligationCause::new(span, self.body_id, traits::TrivialBound),
1839                     empty_env,
1840                     pred,
1841                 );
1842                 self.ocx.register_obligation(obligation);
1843             }
1844         }
1845     }
1846 }
1847
1848 fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
1849     let items = tcx.hir_module_items(module);
1850     items.par_items(|item| tcx.ensure().check_well_formed(item.def_id));
1851     items.par_impl_items(|item| tcx.ensure().check_well_formed(item.def_id));
1852     items.par_trait_items(|item| tcx.ensure().check_well_formed(item.def_id));
1853     items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.def_id));
1854 }
1855
1856 ///////////////////////////////////////////////////////////////////////////
1857 // ADT
1858
1859 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1860 struct AdtVariant<'tcx> {
1861     /// Types of fields in the variant, that must be well-formed.
1862     fields: Vec<AdtField<'tcx>>,
1863
1864     /// Explicit discriminant of this variant (e.g. `A = 123`),
1865     /// that must evaluate to a constant value.
1866     explicit_discr: Option<LocalDefId>,
1867 }
1868
1869 struct AdtField<'tcx> {
1870     ty: Ty<'tcx>,
1871     def_id: LocalDefId,
1872     span: Span,
1873 }
1874
1875 impl<'a, 'tcx> WfCheckingCtxt<'a, 'tcx> {
1876     // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1877     fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1878         let fields = struct_def
1879             .fields()
1880             .iter()
1881             .map(|field| {
1882                 let def_id = self.tcx().hir().local_def_id(field.hir_id);
1883                 let field_ty = self.tcx().type_of(def_id);
1884                 let field_ty = self.normalize(field.ty.span, None, field_ty);
1885                 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1886                 AdtField { ty: field_ty, span: field.ty.span, def_id }
1887             })
1888             .collect();
1889         AdtVariant { fields, explicit_discr: None }
1890     }
1891
1892     fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1893         enum_def
1894             .variants
1895             .iter()
1896             .map(|variant| AdtVariant {
1897                 fields: self.non_enum_variant(&variant.data).fields,
1898                 explicit_discr: variant
1899                     .disr_expr
1900                     .map(|explicit_discr| self.tcx().hir().local_def_id(explicit_discr.hir_id)),
1901             })
1902             .collect()
1903     }
1904 }
1905
1906 fn error_392(
1907     tcx: TyCtxt<'_>,
1908     span: Span,
1909     param_name: Symbol,
1910 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
1911     let mut err = struct_span_err!(tcx.sess, span, E0392, "parameter `{param_name}` is never used");
1912     err.span_label(span, "unused parameter");
1913     err
1914 }
1915
1916 pub fn provide(providers: &mut Providers) {
1917     *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };
1918 }