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