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