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