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