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