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