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