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