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