]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/wfcheck.rs
9e39abe9aa55b73a57b13f7c8ee5eb58ab882a9a
[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         // for a type to be WF, we do not need to check if const trait predicates satisfy.
73         let param_env = self.param_env.without_const();
74         self.ocx.register_obligation(traits::Obligation::new(
75             cause,
76             param_env,
77             ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx()),
78         ));
79     }
80 }
81
82 pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
83     tcx: TyCtxt<'tcx>,
84     span: Span,
85     body_def_id: LocalDefId,
86     f: F,
87 ) where
88     F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>),
89 {
90     let param_env = tcx.param_env(body_def_id);
91     let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id);
92     tcx.infer_ctxt().enter(|ref infcx| {
93         let ocx = ObligationCtxt::new(infcx);
94
95         let assumed_wf_types = ocx.assumed_wf_types(param_env, span, body_def_id);
96
97         let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env };
98
99         if !tcx.features().trivial_bounds {
100             wfcx.check_false_global_bounds()
101         }
102         f(&mut wfcx);
103         let errors = wfcx.select_all_or_error();
104         if !errors.is_empty() {
105             infcx.report_fulfillment_errors(&errors, None, false);
106             return;
107         }
108
109         let mut outlives_environment = OutlivesEnvironment::new(param_env);
110         outlives_environment.add_implied_bounds(infcx, assumed_wf_types, body_id);
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 mut outlives_environment = OutlivesEnvironment::new(param_env);
700         outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id);
701         let region_bound_pairs = outlives_environment.region_bound_pairs();
702
703         add_constraints(&infcx, region_bound_pairs);
704
705         let errors = infcx.resolve_regions(&outlives_environment);
706
707         debug!(?errors, "errors");
708
709         // If we were able to prove that the type outlives the region without
710         // an error, it must be because of the implied or explicit bounds...
711         errors.is_empty()
712     })
713 }
714
715 /// TypeVisitor that looks for uses of GATs like
716 /// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
717 /// the two vectors, `regions` and `types` (depending on their kind). For each
718 /// parameter `Pi` also track the index `i`.
719 struct GATSubstCollector<'tcx> {
720     gat: DefId,
721     // Which region appears and which parameter index its substituted for
722     regions: FxHashSet<(ty::Region<'tcx>, usize)>,
723     // Which params appears and which parameter index its substituted for
724     types: FxHashSet<(Ty<'tcx>, usize)>,
725 }
726
727 impl<'tcx> GATSubstCollector<'tcx> {
728     fn visit<T: TypeFoldable<'tcx>>(
729         gat: DefId,
730         t: T,
731     ) -> (FxHashSet<(ty::Region<'tcx>, usize)>, FxHashSet<(Ty<'tcx>, usize)>) {
732         let mut visitor =
733             GATSubstCollector { gat, regions: FxHashSet::default(), types: FxHashSet::default() };
734         t.visit_with(&mut visitor);
735         (visitor.regions, visitor.types)
736     }
737 }
738
739 impl<'tcx> TypeVisitor<'tcx> for GATSubstCollector<'tcx> {
740     type BreakTy = !;
741
742     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
743         match t.kind() {
744             ty::Projection(p) if p.item_def_id == self.gat => {
745                 for (idx, subst) in p.substs.iter().enumerate() {
746                     match subst.unpack() {
747                         GenericArgKind::Lifetime(lt) if !lt.is_late_bound() => {
748                             self.regions.insert((lt, idx));
749                         }
750                         GenericArgKind::Type(t) => {
751                             self.types.insert((t, idx));
752                         }
753                         _ => {}
754                     }
755                 }
756             }
757             _ => {}
758         }
759         t.super_visit_with(self)
760     }
761 }
762
763 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
764     match ty.kind {
765         hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
766             [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
767             _ => false,
768         },
769         _ => false,
770     }
771 }
772
773 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
774 /// When this is done, suggest using `Self` instead.
775 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
776     let (trait_name, trait_def_id) =
777         match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id())) {
778             hir::Node::Item(item) => match item.kind {
779                 hir::ItemKind::Trait(..) => (item.ident, item.def_id),
780                 _ => return,
781             },
782             _ => return,
783         };
784     let mut trait_should_be_self = vec![];
785     match &item.kind {
786         hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
787             if could_be_self(trait_def_id, ty) =>
788         {
789             trait_should_be_self.push(ty.span)
790         }
791         hir::TraitItemKind::Fn(sig, _) => {
792             for ty in sig.decl.inputs {
793                 if could_be_self(trait_def_id, ty) {
794                     trait_should_be_self.push(ty.span);
795                 }
796             }
797             match sig.decl.output {
798                 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
799                     trait_should_be_self.push(ty.span);
800                 }
801                 _ => {}
802             }
803         }
804         _ => {}
805     }
806     if !trait_should_be_self.is_empty() {
807         if tcx.object_safety_violations(trait_def_id).is_empty() {
808             return;
809         }
810         let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
811         tcx.sess
812             .struct_span_err(
813                 trait_should_be_self,
814                 "associated item referring to unboxed trait object for its own trait",
815             )
816             .span_label(trait_name.span, "in this trait")
817             .multipart_suggestion(
818                 "you might have meant to use `Self` to refer to the implementing type",
819                 sugg,
820                 Applicability::MachineApplicable,
821             )
822             .emit();
823     }
824 }
825
826 fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) {
827     let def_id = impl_item.def_id;
828
829     let (method_sig, span) = match impl_item.kind {
830         hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
831         // Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
832         hir::ImplItemKind::TyAlias(ty) if ty.span != DUMMY_SP => (None, ty.span),
833         _ => (None, impl_item.span),
834     };
835
836     check_associated_item(tcx, def_id, span, method_sig);
837 }
838
839 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
840     match param.kind {
841         // We currently only check wf of const params here.
842         hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
843
844         // Const parameters are well formed if their type is structural match.
845         hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
846             let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
847
848             if tcx.features().adt_const_params {
849                 if let Some(non_structural_match_ty) =
850                     traits::search_for_adt_const_param_violation(param.span, tcx, ty)
851                 {
852                     // We use the same error code in both branches, because this is really the same
853                     // issue: we just special-case the message for type parameters to make it
854                     // clearer.
855                     match non_structural_match_ty.kind() {
856                         ty::Param(_) => {
857                             // Const parameters may not have type parameters as their types,
858                             // because we cannot be sure that the type parameter derives `PartialEq`
859                             // and `Eq` (just implementing them is not enough for `structural_match`).
860                             struct_span_err!(
861                                 tcx.sess,
862                                 hir_ty.span,
863                                 E0741,
864                                 "`{ty}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
865                                 used as the type of a const parameter",
866                             )
867                             .span_label(
868                                 hir_ty.span,
869                                 format!("`{ty}` may not derive both `PartialEq` and `Eq`"),
870                             )
871                             .note(
872                                 "it is not currently possible to use a type parameter as the type of a \
873                                 const parameter",
874                             )
875                             .emit();
876                         }
877                         ty::Float(_) => {
878                             struct_span_err!(
879                                 tcx.sess,
880                                 hir_ty.span,
881                                 E0741,
882                                 "`{ty}` is forbidden as the type of a const generic parameter",
883                             )
884                             .note("floats do not derive `Eq` or `Ord`, which are required for const parameters")
885                             .emit();
886                         }
887                         ty::FnPtr(_) => {
888                             struct_span_err!(
889                                 tcx.sess,
890                                 hir_ty.span,
891                                 E0741,
892                                 "using function pointers as const generic parameters is forbidden",
893                             )
894                             .emit();
895                         }
896                         ty::RawPtr(_) => {
897                             struct_span_err!(
898                                 tcx.sess,
899                                 hir_ty.span,
900                                 E0741,
901                                 "using raw pointers as const generic parameters is forbidden",
902                             )
903                             .emit();
904                         }
905                         _ => {
906                             let mut diag = struct_span_err!(
907                                 tcx.sess,
908                                 hir_ty.span,
909                                 E0741,
910                                 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
911                                 the type of a const parameter",
912                                 non_structural_match_ty,
913                             );
914
915                             if ty == non_structural_match_ty {
916                                 diag.span_label(
917                                     hir_ty.span,
918                                     format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
919                                 );
920                             }
921
922                             diag.emit();
923                         }
924                     }
925                 }
926             } else {
927                 let err_ty_str;
928                 let mut is_ptr = true;
929
930                 let err = match ty.kind() {
931                     ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
932                     ty::FnPtr(_) => Some("function pointers"),
933                     ty::RawPtr(_) => Some("raw pointers"),
934                     _ => {
935                         is_ptr = false;
936                         err_ty_str = format!("`{ty}`");
937                         Some(err_ty_str.as_str())
938                     }
939                 };
940
941                 if let Some(unsupported_type) = err {
942                     if is_ptr {
943                         tcx.sess.span_err(
944                             hir_ty.span,
945                             &format!(
946                                 "using {unsupported_type} as const generic parameters is forbidden",
947                             ),
948                         );
949                     } else {
950                         let mut err = tcx.sess.struct_span_err(
951                             hir_ty.span,
952                             &format!(
953                                 "{unsupported_type} is forbidden as the type of a const generic parameter",
954                             ),
955                         );
956                         err.note("the only supported types are integers, `bool` and `char`");
957                         if tcx.sess.is_nightly_build() {
958                             err.help(
959                             "more complex types are supported with `#![feature(adt_const_params)]`",
960                         );
961                         }
962                         err.emit();
963                     }
964                 }
965             }
966         }
967     }
968 }
969
970 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
971 fn check_associated_item(
972     tcx: TyCtxt<'_>,
973     item_id: LocalDefId,
974     span: Span,
975     sig_if_method: Option<&hir::FnSig<'_>>,
976 ) {
977     let loc = Some(WellFormedLoc::Ty(item_id));
978     enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
979         let item = tcx.associated_item(item_id);
980
981         let self_ty = match item.container {
982             ty::TraitContainer => tcx.types.self_param,
983             ty::ImplContainer => tcx.type_of(item.container_id(tcx)),
984         };
985
986         match item.kind {
987             ty::AssocKind::Const => {
988                 let ty = tcx.type_of(item.def_id);
989                 let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
990                 wfcx.register_wf_obligation(span, loc, ty.into());
991             }
992             ty::AssocKind::Fn => {
993                 let sig = tcx.fn_sig(item.def_id);
994                 let hir_sig = sig_if_method.expect("bad signature for method");
995                 check_fn_or_method(
996                     wfcx,
997                     item.ident(tcx).span,
998                     sig,
999                     hir_sig.decl,
1000                     item.def_id.expect_local(),
1001                 );
1002                 check_method_receiver(wfcx, hir_sig, item, self_ty);
1003             }
1004             ty::AssocKind::Type => {
1005                 if let ty::AssocItemContainer::TraitContainer = item.container {
1006                     check_associated_type_bounds(wfcx, item, span)
1007                 }
1008                 if item.defaultness(tcx).has_value() {
1009                     let ty = tcx.type_of(item.def_id);
1010                     let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
1011                     wfcx.register_wf_obligation(span, loc, ty.into());
1012                 }
1013             }
1014         }
1015     })
1016 }
1017
1018 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
1019     match kind {
1020         ItemKind::Struct(..) => Some(AdtKind::Struct),
1021         ItemKind::Union(..) => Some(AdtKind::Union),
1022         ItemKind::Enum(..) => Some(AdtKind::Enum),
1023         _ => None,
1024     }
1025 }
1026
1027 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
1028 fn check_type_defn<'tcx, F>(
1029     tcx: TyCtxt<'tcx>,
1030     item: &hir::Item<'tcx>,
1031     all_sized: bool,
1032     mut lookup_fields: F,
1033 ) where
1034     F: FnMut(&WfCheckingCtxt<'_, 'tcx>) -> Vec<AdtVariant<'tcx>>,
1035 {
1036     enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1037         let variants = lookup_fields(wfcx);
1038         let packed = tcx.adt_def(item.def_id).repr().packed();
1039
1040         for variant in &variants {
1041             // All field types must be well-formed.
1042             for field in &variant.fields {
1043                 wfcx.register_wf_obligation(
1044                     field.span,
1045                     Some(WellFormedLoc::Ty(field.def_id)),
1046                     field.ty.into(),
1047                 )
1048             }
1049
1050             // For DST, or when drop needs to copy things around, all
1051             // intermediate types must be sized.
1052             let needs_drop_copy = || {
1053                 packed && {
1054                     let ty = variant.fields.last().unwrap().ty;
1055                     let ty = tcx.erase_regions(ty);
1056                     if ty.needs_infer() {
1057                         tcx.sess
1058                             .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
1059                         // Just treat unresolved type expression as if it needs drop.
1060                         true
1061                     } else {
1062                         ty.needs_drop(tcx, tcx.param_env(item.def_id))
1063                     }
1064                 }
1065             };
1066             // All fields (except for possibly the last) should be sized.
1067             let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
1068             let unsized_len = if all_sized { 0 } else { 1 };
1069             for (idx, field) in
1070                 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
1071             {
1072                 let last = idx == variant.fields.len() - 1;
1073                 wfcx.register_bound(
1074                     traits::ObligationCause::new(
1075                         field.span,
1076                         wfcx.body_id,
1077                         traits::FieldSized {
1078                             adt_kind: match item_adt_kind(&item.kind) {
1079                                 Some(i) => i,
1080                                 None => bug!(),
1081                             },
1082                             span: field.span,
1083                             last,
1084                         },
1085                     ),
1086                     wfcx.param_env,
1087                     field.ty,
1088                     tcx.require_lang_item(LangItem::Sized, None),
1089                 );
1090             }
1091
1092             // Explicit `enum` discriminant values must const-evaluate successfully.
1093             if let Some(discr_def_id) = variant.explicit_discr {
1094                 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
1095
1096                 let cause = traits::ObligationCause::new(
1097                     tcx.def_span(discr_def_id),
1098                     wfcx.body_id,
1099                     traits::MiscObligation,
1100                 );
1101                 wfcx.register_obligation(traits::Obligation::new(
1102                     cause,
1103                     wfcx.param_env,
1104                     ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
1105                         ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
1106                         discr_substs,
1107                     )))
1108                     .to_predicate(tcx),
1109                 ));
1110             }
1111         }
1112
1113         check_where_clauses(wfcx, item.span, item.def_id);
1114     });
1115 }
1116
1117 #[instrument(skip(tcx, item))]
1118 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
1119     debug!(?item.def_id);
1120
1121     let trait_def = tcx.trait_def(item.def_id);
1122     if trait_def.is_marker
1123         || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
1124     {
1125         for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
1126             struct_span_err!(
1127                 tcx.sess,
1128                 tcx.def_span(*associated_def_id),
1129                 E0714,
1130                 "marker traits cannot have associated items",
1131             )
1132             .emit();
1133         }
1134     }
1135
1136     enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1137         check_where_clauses(wfcx, item.span, item.def_id)
1138     });
1139
1140     // Only check traits, don't check trait aliases
1141     if let hir::ItemKind::Trait(_, _, _, _, items) = item.kind {
1142         check_gat_where_clauses(tcx, items);
1143     }
1144 }
1145
1146 /// Checks all associated type defaults of trait `trait_def_id`.
1147 ///
1148 /// Assuming the defaults are used, check that all predicates (bounds on the
1149 /// assoc type and where clauses on the trait) hold.
1150 fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
1151     let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
1152
1153     debug!("check_associated_type_bounds: bounds={:?}", bounds);
1154     let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
1155         let normalized_bound = wfcx.normalize(span, None, bound);
1156         traits::wf::predicate_obligations(
1157             wfcx.infcx,
1158             wfcx.param_env,
1159             wfcx.body_id,
1160             normalized_bound,
1161             bound_span,
1162         )
1163     });
1164
1165     wfcx.register_obligations(wf_obligations);
1166 }
1167
1168 fn check_item_fn(
1169     tcx: TyCtxt<'_>,
1170     def_id: LocalDefId,
1171     ident: Ident,
1172     span: Span,
1173     decl: &hir::FnDecl<'_>,
1174 ) {
1175     enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
1176         let sig = tcx.fn_sig(def_id);
1177         check_fn_or_method(wfcx, ident.span, sig, decl, def_id);
1178     })
1179 }
1180
1181 fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
1182     debug!("check_item_type: {:?}", item_id);
1183
1184     enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
1185         let ty = tcx.type_of(item_id);
1186         let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
1187
1188         let mut forbid_unsized = true;
1189         if allow_foreign_ty {
1190             let tail = tcx.struct_tail_erasing_lifetimes(item_ty, wfcx.param_env);
1191             if let ty::Foreign(_) = tail.kind() {
1192                 forbid_unsized = false;
1193             }
1194         }
1195
1196         wfcx.register_wf_obligation(
1197             ty_span,
1198             Some(WellFormedLoc::Ty(item_id)),
1199             item_ty.into(),
1200         );
1201         if forbid_unsized {
1202             wfcx.register_bound(
1203                 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::WellFormed(None)),
1204                 wfcx.param_env,
1205                 item_ty,
1206                 tcx.require_lang_item(LangItem::Sized, None),
1207             );
1208         }
1209
1210         // Ensure that the end result is `Sync` in a non-thread local `static`.
1211         let should_check_for_sync = tcx.static_mutability(item_id.to_def_id())
1212             == Some(hir::Mutability::Not)
1213             && !tcx.is_foreign_item(item_id.to_def_id())
1214             && !tcx.is_thread_local_static(item_id.to_def_id());
1215
1216         if should_check_for_sync {
1217             wfcx.register_bound(
1218                 traits::ObligationCause::new(ty_span, wfcx.body_id, traits::SharedStatic),
1219                 wfcx.param_env,
1220                 item_ty,
1221                 tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
1222             );
1223         }
1224     });
1225 }
1226
1227 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
1228 fn check_impl<'tcx>(
1229     tcx: TyCtxt<'tcx>,
1230     item: &'tcx hir::Item<'tcx>,
1231     ast_self_ty: &hir::Ty<'_>,
1232     ast_trait_ref: &Option<hir::TraitRef<'_>>,
1233     constness: hir::Constness,
1234 ) {
1235     enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
1236         match *ast_trait_ref {
1237             Some(ref ast_trait_ref) => {
1238                 // `#[rustc_reservation_impl]` impls are not real impls and
1239                 // therefore don't need to be WF (the trait's `Self: Trait` predicate
1240                 // won't hold).
1241                 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
1242                 let trait_ref = wfcx.normalize(ast_trait_ref.path.span, None, trait_ref);
1243                 let trait_pred = ty::TraitPredicate {
1244                     trait_ref,
1245                     constness: match constness {
1246                         hir::Constness::Const => ty::BoundConstness::ConstIfConst,
1247                         hir::Constness::NotConst => ty::BoundConstness::NotConst,
1248                     },
1249                     polarity: ty::ImplPolarity::Positive,
1250                 };
1251                 let obligations = traits::wf::trait_obligations(
1252                     wfcx.infcx,
1253                     wfcx.param_env,
1254                     wfcx.body_id,
1255                     &trait_pred,
1256                     ast_trait_ref.path.span,
1257                     item,
1258                 );
1259                 debug!(?obligations);
1260                 wfcx.register_obligations(obligations);
1261             }
1262             None => {
1263                 let self_ty = tcx.type_of(item.def_id);
1264                 let self_ty = wfcx.normalize(item.span, None, self_ty);
1265                 wfcx.register_wf_obligation(
1266                     ast_self_ty.span,
1267                     Some(WellFormedLoc::Ty(item.hir_id().expect_owner())),
1268                     self_ty.into(),
1269                 );
1270             }
1271         }
1272
1273         check_where_clauses(wfcx, item.span, item.def_id);
1274     });
1275 }
1276
1277 /// Checks where-clauses and inline bounds that are declared on `def_id`.
1278 #[instrument(level = "debug", skip(wfcx))]
1279 fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
1280     let infcx = wfcx.infcx;
1281     let tcx = wfcx.tcx();
1282
1283     let predicates = tcx.bound_predicates_of(def_id.to_def_id());
1284     let generics = tcx.generics_of(def_id);
1285
1286     let is_our_default = |def: &ty::GenericParamDef| match def.kind {
1287         GenericParamDefKind::Type { has_default, .. }
1288         | GenericParamDefKind::Const { has_default } => {
1289             has_default && def.index >= generics.parent_count as u32
1290         }
1291         GenericParamDefKind::Lifetime => unreachable!(),
1292     };
1293
1294     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
1295     // For example, this forbids the declaration:
1296     //
1297     //     struct Foo<T = Vec<[u32]>> { .. }
1298     //
1299     // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
1300     for param in &generics.params {
1301         match param.kind {
1302             GenericParamDefKind::Type { .. } => {
1303                 if is_our_default(param) {
1304                     let ty = tcx.type_of(param.def_id);
1305                     // Ignore dependent defaults -- that is, where the default of one type
1306                     // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
1307                     // be sure if it will error or not as user might always specify the other.
1308                     if !ty.needs_subst() {
1309                         wfcx.register_wf_obligation(
1310                             tcx.def_span(param.def_id),
1311                             None,
1312                             ty.into(),
1313                         );
1314                     }
1315                 }
1316             }
1317             GenericParamDefKind::Const { .. } => {
1318                 if is_our_default(param) {
1319                     // FIXME(const_generics_defaults): This
1320                     // is incorrect when dealing with unused substs, for example
1321                     // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
1322                     // we should eagerly error.
1323                     let default_ct = tcx.const_param_default(param.def_id);
1324                     if !default_ct.needs_subst() {
1325                         wfcx.register_wf_obligation(
1326                             tcx.def_span(param.def_id),
1327                             None,
1328                             default_ct.into(),
1329                         );
1330                     }
1331                 }
1332             }
1333             // Doesn't have defaults.
1334             GenericParamDefKind::Lifetime => {}
1335         }
1336     }
1337
1338     // Check that trait predicates are WF when params are substituted by their defaults.
1339     // We don't want to overly constrain the predicates that may be written but we want to
1340     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
1341     // Therefore we check if a predicate which contains a single type param
1342     // with a concrete default is WF with that default substituted.
1343     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
1344     //
1345     // First we build the defaulted substitution.
1346     let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| {
1347         match param.kind {
1348             GenericParamDefKind::Lifetime => {
1349                 // All regions are identity.
1350                 tcx.mk_param_from_def(param)
1351             }
1352
1353             GenericParamDefKind::Type { .. } => {
1354                 // If the param has a default, ...
1355                 if is_our_default(param) {
1356                     let default_ty = tcx.type_of(param.def_id);
1357                     // ... and it's not a dependent default, ...
1358                     if !default_ty.needs_subst() {
1359                         // ... then substitute it with the default.
1360                         return default_ty.into();
1361                     }
1362                 }
1363
1364                 tcx.mk_param_from_def(param)
1365             }
1366             GenericParamDefKind::Const { .. } => {
1367                 // If the param has a default, ...
1368                 if is_our_default(param) {
1369                     let default_ct = tcx.const_param_default(param.def_id);
1370                     // ... and it's not a dependent default, ...
1371                     if !default_ct.needs_subst() {
1372                         // ... then substitute it with the default.
1373                         return default_ct.into();
1374                     }
1375                 }
1376
1377                 tcx.mk_param_from_def(param)
1378             }
1379         }
1380     });
1381
1382     // Now we build the substituted predicates.
1383     let default_obligations = predicates
1384         .0
1385         .predicates
1386         .iter()
1387         .flat_map(|&(pred, sp)| {
1388             #[derive(Default)]
1389             struct CountParams {
1390                 params: FxHashSet<u32>,
1391             }
1392             impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
1393                 type BreakTy = ();
1394
1395                 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1396                     if let ty::Param(param) = t.kind() {
1397                         self.params.insert(param.index);
1398                     }
1399                     t.super_visit_with(self)
1400                 }
1401
1402                 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1403                     ControlFlow::BREAK
1404                 }
1405
1406                 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
1407                     if let ty::ConstKind::Param(param) = c.kind() {
1408                         self.params.insert(param.index);
1409                     }
1410                     c.super_visit_with(self)
1411                 }
1412             }
1413             let mut param_count = CountParams::default();
1414             let has_region = pred.visit_with(&mut param_count).is_break();
1415             let substituted_pred = predicates.rebind(pred).subst(tcx, substs);
1416             // Don't check non-defaulted params, dependent defaults (including lifetimes)
1417             // or preds with multiple params.
1418             if substituted_pred.has_param_types_or_consts()
1419                 || param_count.params.len() > 1
1420                 || has_region
1421             {
1422                 None
1423             } else if predicates.0.predicates.iter().any(|&(p, _)| p == substituted_pred) {
1424                 // Avoid duplication of predicates that contain no parameters, for example.
1425                 None
1426             } else {
1427                 Some((substituted_pred, sp))
1428             }
1429         })
1430         .map(|(pred, sp)| {
1431             // Convert each of those into an obligation. So if you have
1432             // something like `struct Foo<T: Copy = String>`, we would
1433             // take that predicate `T: Copy`, substitute to `String: Copy`
1434             // (actually that happens in the previous `flat_map` call),
1435             // and then try to prove it (in this case, we'll fail).
1436             //
1437             // Note the subtle difference from how we handle `predicates`
1438             // below: there, we are not trying to prove those predicates
1439             // to be *true* but merely *well-formed*.
1440             let pred = wfcx.normalize(sp, None, pred);
1441             let cause = traits::ObligationCause::new(
1442                 sp,
1443                 wfcx.body_id,
1444                 traits::ItemObligation(def_id.to_def_id()),
1445             );
1446             traits::Obligation::new(cause, wfcx.param_env, pred)
1447         });
1448
1449     let predicates = predicates.0.instantiate_identity(tcx);
1450
1451     let predicates = wfcx.normalize(span, None, predicates);
1452
1453     debug!(?predicates.predicates);
1454     assert_eq!(predicates.predicates.len(), predicates.spans.len());
1455     let wf_obligations =
1456         iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
1457             traits::wf::predicate_obligations(infcx, wfcx.param_env.without_const(), wfcx.body_id, p, sp)
1458         });
1459
1460     let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
1461     wfcx.register_obligations(obligations);
1462 }
1463
1464 #[tracing::instrument(level = "debug", skip(wfcx, span, hir_decl))]
1465 fn check_fn_or_method<'tcx>(
1466     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1467     span: Span,
1468     sig: ty::PolyFnSig<'tcx>,
1469     hir_decl: &hir::FnDecl<'_>,
1470     def_id: LocalDefId,
1471 ) {
1472     let tcx = wfcx.tcx();
1473     let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
1474
1475     // Normalize the input and output types one at a time, using a different
1476     // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
1477     // on the entire `FnSig`, since this would use the same `WellFormedLoc`
1478     // for each type, preventing the HIR wf check from generating
1479     // a nice error message.
1480     let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
1481     inputs_and_output = tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
1482         wfcx.normalize(
1483             span,
1484             Some(WellFormedLoc::Param {
1485                 function: def_id,
1486                 // Note that the `param_idx` of the output type is
1487                 // one greater than the index of the last input type.
1488                 param_idx: i.try_into().unwrap(),
1489             }),
1490             ty,
1491         )
1492     }));
1493     // Manually call `normalize_associated_types_in` on the other types
1494     // in `FnSig`. This ensures that if the types of these fields
1495     // ever change to include projections, we will start normalizing
1496     // them automatically.
1497     let sig = ty::FnSig {
1498         inputs_and_output,
1499         c_variadic: wfcx.normalize(span, None, c_variadic),
1500         unsafety: wfcx.normalize(span, None, unsafety),
1501         abi: wfcx.normalize(span, None, abi),
1502     };
1503
1504     for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
1505         wfcx.register_wf_obligation(
1506             ty.span,
1507             Some(WellFormedLoc::Param { function: def_id, param_idx: i.try_into().unwrap() }),
1508             input_ty.into(),
1509         );
1510     }
1511
1512     wfcx.register_wf_obligation(
1513         hir_decl.output.span(),
1514         None,
1515         sig.output().into(),
1516     );
1517
1518     check_where_clauses(wfcx, span, def_id);
1519 }
1520
1521 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1522      `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1523      of the previous types except `Self`)";
1524
1525 #[tracing::instrument(level = "debug", skip(wfcx))]
1526 fn check_method_receiver<'tcx>(
1527     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1528     fn_sig: &hir::FnSig<'_>,
1529     method: &ty::AssocItem,
1530     self_ty: Ty<'tcx>,
1531 ) {
1532     let tcx = wfcx.tcx();
1533
1534     if !method.fn_has_self_parameter {
1535         return;
1536     }
1537
1538     let span = fn_sig.decl.inputs[0].span;
1539
1540     let sig = tcx.fn_sig(method.def_id);
1541     let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
1542     let sig = wfcx.normalize(span, None, sig);
1543
1544     debug!("check_method_receiver: sig={:?}", sig);
1545
1546     let self_ty = wfcx.normalize(span, None, self_ty);
1547
1548     let receiver_ty = sig.inputs()[0];
1549     let receiver_ty = wfcx.normalize(span, None, receiver_ty);
1550
1551     if tcx.features().arbitrary_self_types {
1552         if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1553             // Report error; `arbitrary_self_types` was enabled.
1554             e0307(tcx, span, receiver_ty);
1555         }
1556     } else {
1557         if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
1558             if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
1559                 // Report error; would have worked with `arbitrary_self_types`.
1560                 feature_err(
1561                     &tcx.sess.parse_sess,
1562                     sym::arbitrary_self_types,
1563                     span,
1564                     &format!(
1565                         "`{receiver_ty}` cannot be used as the type of `self` without \
1566                          the `arbitrary_self_types` feature",
1567                     ),
1568                 )
1569                 .help(HELP_FOR_SELF_TYPE)
1570                 .emit();
1571             } else {
1572                 // Report error; would not have worked with `arbitrary_self_types`.
1573                 e0307(tcx, span, receiver_ty);
1574             }
1575         }
1576     }
1577 }
1578
1579 fn e0307<'tcx>(tcx: TyCtxt<'tcx>, span: Span, receiver_ty: Ty<'_>) {
1580     struct_span_err!(
1581         tcx.sess.diagnostic(),
1582         span,
1583         E0307,
1584         "invalid `self` parameter type: {receiver_ty}"
1585     )
1586     .note("type of `self` must be `Self` or a type that dereferences to it")
1587     .help(HELP_FOR_SELF_TYPE)
1588     .emit();
1589 }
1590
1591 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1592 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1593 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1594 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1595 /// `Deref<Target = self_ty>`.
1596 ///
1597 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1598 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1599 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1600 fn receiver_is_valid<'tcx>(
1601     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1602     span: Span,
1603     receiver_ty: Ty<'tcx>,
1604     self_ty: Ty<'tcx>,
1605     arbitrary_self_types_enabled: bool,
1606 ) -> bool {
1607     let infcx = wfcx.infcx;
1608     let tcx = wfcx.tcx();
1609     let cause =
1610         ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver);
1611
1612     let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
1613
1614     // `self: Self` is always valid.
1615     if can_eq_self(receiver_ty) {
1616         if let Err(err) = wfcx.equate_types(&cause, wfcx.param_env, self_ty, receiver_ty) {
1617             infcx.report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
1618         }
1619         return true;
1620     }
1621
1622     let mut autoderef =
1623         Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty, span);
1624
1625     // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1626     if arbitrary_self_types_enabled {
1627         autoderef = autoderef.include_raw_pointers();
1628     }
1629
1630     // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1631     autoderef.next();
1632
1633     let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, None);
1634
1635     // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1636     loop {
1637         if let Some((potential_self_ty, _)) = autoderef.next() {
1638             debug!(
1639                 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1640                 potential_self_ty, self_ty
1641             );
1642
1643             if can_eq_self(potential_self_ty) {
1644                 wfcx.register_obligations(autoderef.into_obligations());
1645
1646                 if let Err(err) =
1647                     wfcx.equate_types(&cause, wfcx.param_env, self_ty, potential_self_ty)
1648                 {
1649                     infcx.report_mismatched_types(&cause, self_ty, potential_self_ty, err).emit();
1650                 }
1651
1652                 break;
1653             } else {
1654                 // Without `feature(arbitrary_self_types)`, we require that each step in the
1655                 // deref chain implement `receiver`
1656                 if !arbitrary_self_types_enabled
1657                     && !receiver_is_implemented(
1658                         wfcx,
1659                         receiver_trait_def_id,
1660                         cause.clone(),
1661                         potential_self_ty,
1662                     )
1663                 {
1664                     return false;
1665                 }
1666             }
1667         } else {
1668             debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1669             // If the receiver already has errors reported due to it, consider it valid to avoid
1670             // unnecessary errors (#58712).
1671             return receiver_ty.references_error();
1672         }
1673     }
1674
1675     // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1676     if !arbitrary_self_types_enabled
1677         && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1678     {
1679         return false;
1680     }
1681
1682     true
1683 }
1684
1685 fn receiver_is_implemented<'tcx>(
1686     wfcx: &WfCheckingCtxt<'_, 'tcx>,
1687     receiver_trait_def_id: DefId,
1688     cause: ObligationCause<'tcx>,
1689     receiver_ty: Ty<'tcx>,
1690 ) -> bool {
1691     let tcx = wfcx.tcx();
1692     let trait_ref = ty::Binder::dummy(ty::TraitRef {
1693         def_id: receiver_trait_def_id,
1694         substs: tcx.mk_substs_trait(receiver_ty, &[]),
1695     });
1696
1697     let obligation =
1698         traits::Obligation::new(cause, wfcx.param_env, trait_ref.without_const().to_predicate(tcx));
1699
1700     if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
1701         true
1702     } else {
1703         debug!(
1704             "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1705             receiver_ty
1706         );
1707         false
1708     }
1709 }
1710
1711 fn check_variances_for_type_defn<'tcx>(
1712     tcx: TyCtxt<'tcx>,
1713     item: &hir::Item<'tcx>,
1714     hir_generics: &hir::Generics<'_>,
1715 ) {
1716     let ty = tcx.type_of(item.def_id);
1717     if tcx.has_error_field(ty) {
1718         return;
1719     }
1720
1721     let ty_predicates = tcx.predicates_of(item.def_id);
1722     assert_eq!(ty_predicates.parent, None);
1723     let variances = tcx.variances_of(item.def_id);
1724
1725     let mut constrained_parameters: FxHashSet<_> = variances
1726         .iter()
1727         .enumerate()
1728         .filter(|&(_, &variance)| variance != ty::Bivariant)
1729         .map(|(index, _)| Parameter(index as u32))
1730         .collect();
1731
1732     identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1733
1734     // Lazily calculated because it is only needed in case of an error.
1735     let explicitly_bounded_params = LazyCell::new(|| {
1736         let icx = crate::collect::ItemCtxt::new(tcx, item.def_id.to_def_id());
1737         hir_generics
1738             .predicates
1739             .iter()
1740             .filter_map(|predicate| match predicate {
1741                 hir::WherePredicate::BoundPredicate(predicate) => {
1742                     match icx.to_ty(predicate.bounded_ty).kind() {
1743                         ty::Param(data) => Some(Parameter(data.index)),
1744                         _ => None,
1745                     }
1746                 }
1747                 _ => None,
1748             })
1749             .collect::<FxHashSet<_>>()
1750     });
1751
1752     for (index, _) in variances.iter().enumerate() {
1753         let parameter = Parameter(index as u32);
1754
1755         if constrained_parameters.contains(&parameter) {
1756             continue;
1757         }
1758
1759         let param = &hir_generics.params[index];
1760
1761         match param.name {
1762             hir::ParamName::Error => {}
1763             _ => {
1764                 let has_explicit_bounds = explicitly_bounded_params.contains(&parameter);
1765                 report_bivariance(tcx, param, has_explicit_bounds);
1766             }
1767         }
1768     }
1769 }
1770
1771 fn report_bivariance(
1772     tcx: TyCtxt<'_>,
1773     param: &rustc_hir::GenericParam<'_>,
1774     has_explicit_bounds: bool,
1775 ) -> ErrorGuaranteed {
1776     let span = param.span;
1777     let param_name = param.name.ident().name;
1778     let mut err = error_392(tcx, span, param_name);
1779
1780     let suggested_marker_id = tcx.lang_items().phantom_data();
1781     // Help is available only in presence of lang items.
1782     let msg = if let Some(def_id) = suggested_marker_id {
1783         format!(
1784             "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1785             param_name,
1786             tcx.def_path_str(def_id),
1787         )
1788     } else {
1789         format!("consider removing `{param_name}` or referring to it in a field")
1790     };
1791     err.help(&msg);
1792
1793     if matches!(param.kind, hir::GenericParamKind::Type { .. }) && !has_explicit_bounds {
1794         err.help(&format!(
1795             "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1796             param_name
1797         ));
1798     }
1799     err.emit()
1800 }
1801
1802 impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
1803     /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1804     /// aren't true.
1805     fn check_false_global_bounds(&mut self) {
1806         let tcx = self.ocx.infcx.tcx;
1807         let mut span = self.span;
1808         let empty_env = ty::ParamEnv::empty();
1809
1810         let def_id = tcx.hir().local_def_id(self.body_id);
1811         let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied();
1812         // Check elaborated bounds.
1813         let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
1814
1815         for obligation in implied_obligations {
1816             // We lower empty bounds like `Vec<dyn Copy>:` as
1817             // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
1818             // regular WF checking
1819             if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
1820                 continue;
1821             }
1822             let pred = obligation.predicate;
1823             // Match the existing behavior.
1824             if pred.is_global() && !pred.has_late_bound_regions() {
1825                 let pred = self.normalize(span, None, pred);
1826                 let hir_node = tcx.hir().find(self.body_id);
1827
1828                 // only use the span of the predicate clause (#90869)
1829
1830                 if let Some(hir::Generics { predicates, .. }) =
1831                     hir_node.and_then(|node| node.generics())
1832                 {
1833                     let obligation_span = obligation.cause.span();
1834
1835                     span = predicates
1836                         .iter()
1837                         // There seems to be no better way to find out which predicate we are in
1838                         .find(|pred| pred.span().contains(obligation_span))
1839                         .map(|pred| pred.span())
1840                         .unwrap_or(obligation_span);
1841                 }
1842
1843                 let obligation = traits::Obligation::new(
1844                     traits::ObligationCause::new(span, self.body_id, traits::TrivialBound),
1845                     empty_env,
1846                     pred,
1847                 );
1848                 self.ocx.register_obligation(obligation);
1849             }
1850         }
1851     }
1852 }
1853
1854 fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
1855     let items = tcx.hir_module_items(module);
1856     items.par_items(|item| tcx.ensure().check_well_formed(item.def_id));
1857     items.par_impl_items(|item| tcx.ensure().check_well_formed(item.def_id));
1858     items.par_trait_items(|item| tcx.ensure().check_well_formed(item.def_id));
1859     items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.def_id));
1860 }
1861
1862 ///////////////////////////////////////////////////////////////////////////
1863 // ADT
1864
1865 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1866 struct AdtVariant<'tcx> {
1867     /// Types of fields in the variant, that must be well-formed.
1868     fields: Vec<AdtField<'tcx>>,
1869
1870     /// Explicit discriminant of this variant (e.g. `A = 123`),
1871     /// that must evaluate to a constant value.
1872     explicit_discr: Option<LocalDefId>,
1873 }
1874
1875 struct AdtField<'tcx> {
1876     ty: Ty<'tcx>,
1877     def_id: LocalDefId,
1878     span: Span,
1879 }
1880
1881 impl<'a, 'tcx> WfCheckingCtxt<'a, 'tcx> {
1882     // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1883     fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1884         let fields = struct_def
1885             .fields()
1886             .iter()
1887             .map(|field| {
1888                 let def_id = self.tcx().hir().local_def_id(field.hir_id);
1889                 let field_ty = self.tcx().type_of(def_id);
1890                 let field_ty = self.normalize(field.ty.span, None, field_ty);
1891                 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1892                 AdtField { ty: field_ty, span: field.ty.span, def_id }
1893             })
1894             .collect();
1895         AdtVariant { fields, explicit_discr: None }
1896     }
1897
1898     fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1899         enum_def
1900             .variants
1901             .iter()
1902             .map(|variant| AdtVariant {
1903                 fields: self.non_enum_variant(&variant.data).fields,
1904                 explicit_discr: variant
1905                     .disr_expr
1906                     .map(|explicit_discr| self.tcx().hir().local_def_id(explicit_discr.hir_id)),
1907             })
1908             .collect()
1909     }
1910 }
1911
1912 fn error_392(
1913     tcx: TyCtxt<'_>,
1914     span: Span,
1915     param_name: Symbol,
1916 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
1917     let mut err = struct_span_err!(tcx.sess, span, E0392, "parameter `{param_name}` is never used");
1918     err.span_label(span, "unused parameter");
1919     err
1920 }
1921
1922 pub fn provide(providers: &mut Providers) {
1923     *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };
1924 }