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