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