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