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