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