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