]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/wfcheck.rs
Auto merge of #79635 - lcnr:const-eval-idk, r=oli-obk
[rust.git] / compiler / rustc_typeck / src / check / wfcheck.rs
1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
3
4 use rustc_ast as ast;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
7 use rustc_hir as hir;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_hir::intravisit as hir_visit;
10 use rustc_hir::intravisit::Visitor;
11 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
12 use rustc_hir::lang_items::LangItem;
13 use rustc_hir::ItemKind;
14 use rustc_middle::hir::map as hir_map;
15 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
16 use rustc_middle::ty::trait_def::TraitSpecializationKind;
17 use rustc_middle::ty::{
18     self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
19 };
20 use rustc_session::parse::feature_err;
21 use rustc_span::symbol::{sym, Ident, Symbol};
22 use rustc_span::Span;
23 use rustc_trait_selection::opaque_types::may_define_opaque_type;
24 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
25 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
26
27 use std::ops::ControlFlow;
28
29 /// Helper type of a temporary returned by `.for_item(...)`.
30 /// This is necessary because we can't write the following bound:
31 ///
32 /// ```rust
33 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
34 /// ```
35 struct CheckWfFcxBuilder<'tcx> {
36     inherited: super::InheritedBuilder<'tcx>,
37     id: hir::HirId,
38     span: Span,
39     param_env: ty::ParamEnv<'tcx>,
40 }
41
42 impl<'tcx> CheckWfFcxBuilder<'tcx> {
43     fn with_fcx<F>(&mut self, f: F)
44     where
45         F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>, TyCtxt<'tcx>) -> Vec<Ty<'tcx>>,
46     {
47         let id = self.id;
48         let span = self.span;
49         let param_env = self.param_env;
50         self.inherited.enter(|inh| {
51             let fcx = FnCtxt::new(&inh, param_env, id);
52             if !inh.tcx.features().trivial_bounds {
53                 // As predicates are cached rather than obligations, this
54                 // needsto be called first so that they are checked with an
55                 // empty `param_env`.
56                 check_false_global_bounds(&fcx, span, id);
57             }
58             let wf_tys = f(&fcx, fcx.tcx);
59             fcx.select_all_obligations_or_error();
60             fcx.regionck_item(id, span, &wf_tys);
61         });
62     }
63 }
64
65 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
66 /// well-formed, meaning that they do not require any constraints not declared in the struct
67 /// definition itself. For example, this definition would be illegal:
68 ///
69 /// ```rust
70 /// struct Ref<'a, T> { x: &'a T }
71 /// ```
72 ///
73 /// because the type did not declare that `T:'a`.
74 ///
75 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
76 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
77 /// the types first.
78 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
79     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
80     let item = tcx.hir().expect_item(hir_id);
81
82     debug!(
83         "check_item_well_formed(it.hir_id={:?}, it.name={})",
84         item.hir_id,
85         tcx.def_path_str(def_id.to_def_id())
86     );
87
88     match item.kind {
89         // Right now we check that every default trait implementation
90         // has an implementation of itself. Basically, a case like:
91         //
92         //     impl Trait for T {}
93         //
94         // has a requirement of `T: Trait` which was required for default
95         // method implementations. Although this could be improved now that
96         // there's a better infrastructure in place for this, it's being left
97         // for a follow-up work.
98         //
99         // Since there's such a requirement, we need to check *just* positive
100         // implementations, otherwise things like:
101         //
102         //     impl !Send for T {}
103         //
104         // won't be allowed unless there's an *explicit* implementation of `Send`
105         // for `T`
106         hir::ItemKind::Impl {
107             defaultness,
108             defaultness_span,
109             polarity,
110             ref of_trait,
111             ref self_ty,
112             ..
113         } => {
114             let is_auto = tcx
115                 .impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
116                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
117             if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
118                 let sp = of_trait.as_ref().map(|t| t.path.span).unwrap_or(item.span);
119                 let mut err =
120                     tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
121                 err.span_labels(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), polarity) {
127                 (ty::ImplPolarity::Positive, _) => {
128                     check_impl(tcx, item, self_ty, 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 { .. } = defaultness {
133                         let mut spans = vec![span];
134                         spans.extend(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.hir_id, item.ident, item.span, sig.decl);
152         }
153         hir::ItemKind::Static(ref ty, ..) => {
154             check_item_type(tcx, item.hir_id, ty.span, false);
155         }
156         hir::ItemKind::Const(ref ty, ..) => {
157             check_item_type(tcx, item.hir_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(ref decl, ..) => {
164                         check_item_fn(tcx, it.hir_id, it.ident, it.span, decl)
165                     }
166                     hir::ForeignItemKind::Static(ref ty, ..) => {
167                         check_item_type(tcx, it.hir_id, ty.span, true)
168                     }
169                     hir::ForeignItemKind::Type => (),
170                 }
171             }
172         }
173         hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
174             check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
175
176             check_variances_for_type_defn(tcx, item, ast_generics);
177         }
178         hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
179             check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
180
181             check_variances_for_type_defn(tcx, item, ast_generics);
182         }
183         hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
184             check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
185
186             check_variances_for_type_defn(tcx, item, ast_generics);
187         }
188         hir::ItemKind::Trait(..) => {
189             check_trait(tcx, item);
190         }
191         hir::ItemKind::TraitAlias(..) => {
192             check_trait(tcx, item);
193         }
194         _ => {}
195     }
196 }
197
198 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
199     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
200     let trait_item = tcx.hir().expect_trait_item(hir_id);
201
202     let method_sig = match trait_item.kind {
203         hir::TraitItemKind::Fn(ref sig, _) => Some(sig),
204         _ => None,
205     };
206     check_object_unsafe_self_trait_by_name(tcx, &trait_item);
207     check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
208 }
209
210 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
211     match ty.kind {
212         hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
213             [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
214             _ => false,
215         },
216         _ => false,
217     }
218 }
219
220 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
221 /// When this is done, suggest using `Self` instead.
222 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
223     let (trait_name, trait_def_id) = match tcx.hir().get(tcx.hir().get_parent_item(item.hir_id)) {
224         hir::Node::Item(item) => match item.kind {
225             hir::ItemKind::Trait(..) => (item.ident, tcx.hir().local_def_id(item.hir_id)),
226             _ => return,
227         },
228         _ => return,
229     };
230     let mut trait_should_be_self = vec![];
231     match &item.kind {
232         hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
233             if could_be_self(trait_def_id, ty) =>
234         {
235             trait_should_be_self.push(ty.span)
236         }
237         hir::TraitItemKind::Fn(sig, _) => {
238             for ty in sig.decl.inputs {
239                 if could_be_self(trait_def_id, ty) {
240                     trait_should_be_self.push(ty.span);
241                 }
242             }
243             match sig.decl.output {
244                 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
245                     trait_should_be_self.push(ty.span);
246                 }
247                 _ => {}
248             }
249         }
250         _ => {}
251     }
252     if !trait_should_be_self.is_empty() {
253         if tcx.object_safety_violations(trait_def_id).is_empty() {
254             return;
255         }
256         let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
257         tcx.sess
258             .struct_span_err(
259                 trait_should_be_self,
260                 "associated item referring to unboxed trait object for its own trait",
261             )
262             .span_label(trait_name.span, "in this trait")
263             .multipart_suggestion(
264                 "you might have meant to use `Self` to refer to the implementing type",
265                 sugg,
266                 Applicability::MachineApplicable,
267             )
268             .emit();
269     }
270 }
271
272 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
273     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
274     let impl_item = tcx.hir().expect_impl_item(hir_id);
275
276     let method_sig = match impl_item.kind {
277         hir::ImplItemKind::Fn(ref sig, _) => Some(sig),
278         _ => None,
279     };
280
281     check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
282 }
283
284 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
285     match param.kind {
286         // We currently only check wf of const params here.
287         hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
288
289         // Const parameters are well formed if their
290         // type is structural match.
291         hir::GenericParamKind::Const { ty: hir_ty } => {
292             let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
293
294             let err_ty_str;
295             let mut is_ptr = true;
296             let err = if tcx.features().min_const_generics {
297                 match ty.kind() {
298                     ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
299                     ty::FnPtr(_) => Some("function pointers"),
300                     ty::RawPtr(_) => Some("raw pointers"),
301                     _ => {
302                         is_ptr = false;
303                         err_ty_str = format!("`{}`", ty);
304                         Some(err_ty_str.as_str())
305                     }
306                 }
307             } else {
308                 match ty.peel_refs().kind() {
309                     ty::FnPtr(_) => Some("function pointers"),
310                     ty::RawPtr(_) => Some("raw pointers"),
311                     _ => None,
312                 }
313             };
314             if let Some(unsupported_type) = err {
315                 if is_ptr {
316                     tcx.sess.span_err(
317                         hir_ty.span,
318                         &format!(
319                             "using {} as const generic parameters is forbidden",
320                             unsupported_type
321                         ),
322                     )
323                 } else {
324                     tcx.sess
325                         .struct_span_err(
326                             hir_ty.span,
327                             &format!(
328                                 "{} is forbidden as the type of a const generic parameter",
329                                 unsupported_type
330                             ),
331                         )
332                         .note("the only supported types are integers, `bool` and `char`")
333                         .help("more complex types are supported with `#[feature(const_generics)]`")
334                         .emit()
335                 }
336             };
337
338             if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
339                 .is_some()
340             {
341                 // We use the same error code in both branches, because this is really the same
342                 // issue: we just special-case the message for type parameters to make it
343                 // clearer.
344                 if let ty::Param(_) = ty.peel_refs().kind() {
345                     // Const parameters may not have type parameters as their types,
346                     // because we cannot be sure that the type parameter derives `PartialEq`
347                     // and `Eq` (just implementing them is not enough for `structural_match`).
348                     struct_span_err!(
349                         tcx.sess,
350                         hir_ty.span,
351                         E0741,
352                         "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
353                             used as the type of a const parameter",
354                         ty,
355                     )
356                     .span_label(
357                         hir_ty.span,
358                         format!("`{}` may not derive both `PartialEq` and `Eq`", ty),
359                     )
360                     .note(
361                         "it is not currently possible to use a type parameter as the type of a \
362                             const parameter",
363                     )
364                     .emit();
365                 } else {
366                     struct_span_err!(
367                         tcx.sess,
368                         hir_ty.span,
369                         E0741,
370                         "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
371                             the type of a const parameter",
372                         ty,
373                     )
374                     .span_label(
375                         hir_ty.span,
376                         format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
377                     )
378                     .emit();
379                 }
380             }
381         }
382     }
383 }
384
385 fn check_associated_item(
386     tcx: TyCtxt<'_>,
387     item_id: hir::HirId,
388     span: Span,
389     sig_if_method: Option<&hir::FnSig<'_>>,
390 ) {
391     debug!("check_associated_item: {:?}", item_id);
392
393     let code = ObligationCauseCode::MiscObligation;
394     for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
395         let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
396
397         let (mut implied_bounds, self_ty) = match item.container {
398             ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
399             ty::ImplContainer(def_id) => {
400                 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
401             }
402         };
403
404         match item.kind {
405             ty::AssocKind::Const => {
406                 let ty = fcx.tcx.type_of(item.def_id);
407                 let ty = fcx.normalize_associated_types_in(span, ty);
408                 fcx.register_wf_obligation(ty.into(), span, code.clone());
409             }
410             ty::AssocKind::Fn => {
411                 let sig = fcx.tcx.fn_sig(item.def_id);
412                 let sig = fcx.normalize_associated_types_in(span, sig);
413                 let hir_sig = sig_if_method.expect("bad signature for method");
414                 check_fn_or_method(
415                     tcx,
416                     fcx,
417                     item.ident.span,
418                     sig,
419                     hir_sig.decl,
420                     item.def_id,
421                     &mut implied_bounds,
422                 );
423                 check_method_receiver(fcx, hir_sig, &item, self_ty);
424             }
425             ty::AssocKind::Type => {
426                 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
427                     check_associated_type_bounds(fcx, item, span)
428                 }
429                 if item.defaultness.has_value() {
430                     let ty = fcx.tcx.type_of(item.def_id);
431                     let ty = fcx.normalize_associated_types_in(span, ty);
432                     fcx.register_wf_obligation(ty.into(), span, code.clone());
433                 }
434             }
435         }
436
437         implied_bounds
438     })
439 }
440
441 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
442     for_id(tcx, item.hir_id, item.span)
443 }
444
445 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
446     let def_id = tcx.hir().local_def_id(id);
447     CheckWfFcxBuilder {
448         inherited: Inherited::build(tcx, def_id),
449         id,
450         span,
451         param_env: tcx.param_env(def_id),
452     }
453 }
454
455 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
456     match kind {
457         ItemKind::Struct(..) => Some(AdtKind::Struct),
458         ItemKind::Union(..) => Some(AdtKind::Union),
459         ItemKind::Enum(..) => Some(AdtKind::Enum),
460         _ => None,
461     }
462 }
463
464 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
465 fn check_type_defn<'tcx, F>(
466     tcx: TyCtxt<'tcx>,
467     item: &hir::Item<'tcx>,
468     all_sized: bool,
469     mut lookup_fields: F,
470 ) where
471     F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
472 {
473     for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
474         let variants = lookup_fields(fcx);
475         let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
476         let packed = fcx.tcx.adt_def(def_id).repr.packed();
477
478         for variant in &variants {
479             // For DST, or when drop needs to copy things around, all
480             // intermediate types must be sized.
481             let needs_drop_copy = || {
482                 packed && {
483                     let ty = variant.fields.last().unwrap().ty;
484                     let ty = fcx.tcx.erase_regions(ty);
485                     if ty.needs_infer() {
486                         fcx_tcx
487                             .sess
488                             .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
489                         // Just treat unresolved type expression as if it needs drop.
490                         true
491                     } else {
492                         ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
493                     }
494                 }
495             };
496             let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
497             let unsized_len = if all_sized { 0 } else { 1 };
498             for (idx, field) in
499                 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
500             {
501                 let last = idx == variant.fields.len() - 1;
502                 fcx.register_bound(
503                     field.ty,
504                     fcx.tcx.require_lang_item(LangItem::Sized, None),
505                     traits::ObligationCause::new(
506                         field.span,
507                         fcx.body_id,
508                         traits::FieldSized {
509                             adt_kind: match item_adt_kind(&item.kind) {
510                                 Some(i) => i,
511                                 None => bug!(),
512                             },
513                             span: field.span,
514                             last,
515                         },
516                     ),
517                 );
518             }
519
520             // All field types must be well-formed.
521             for field in &variant.fields {
522                 fcx.register_wf_obligation(
523                     field.ty.into(),
524                     field.span,
525                     ObligationCauseCode::MiscObligation,
526                 )
527             }
528
529             // Explicit `enum` discriminant values must const-evaluate successfully.
530             if let Some(discr_def_id) = variant.explicit_discr {
531                 let discr_substs =
532                     InternalSubsts::identity_for_item(fcx.tcx, discr_def_id.to_def_id());
533
534                 let cause = traits::ObligationCause::new(
535                     fcx.tcx.def_span(discr_def_id),
536                     fcx.body_id,
537                     traits::MiscObligation,
538                 );
539                 fcx.register_predicate(traits::Obligation::new(
540                     cause,
541                     fcx.param_env,
542                     ty::PredicateAtom::ConstEvaluatable(
543                         ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
544                         discr_substs,
545                     )
546                     .to_predicate(fcx.tcx),
547                 ));
548             }
549         }
550
551         check_where_clauses(tcx, fcx, item.span, def_id.to_def_id(), None);
552
553         // No implied bounds in a struct definition.
554         vec![]
555     });
556 }
557
558 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
559     debug!("check_trait: {:?}", item.hir_id);
560
561     let trait_def_id = tcx.hir().local_def_id(item.hir_id);
562
563     let trait_def = tcx.trait_def(trait_def_id);
564     if trait_def.is_marker
565         || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
566     {
567         for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
568             struct_span_err!(
569                 tcx.sess,
570                 tcx.def_span(*associated_def_id),
571                 E0714,
572                 "marker traits cannot have associated items",
573             )
574             .emit();
575         }
576     }
577
578     for_item(tcx, item).with_fcx(|fcx, _| {
579         check_where_clauses(tcx, fcx, item.span, trait_def_id.to_def_id(), None);
580
581         vec![]
582     });
583 }
584
585 /// Checks all associated type defaults of trait `trait_def_id`.
586 ///
587 /// Assuming the defaults are used, check that all predicates (bounds on the
588 /// assoc type and where clauses on the trait) hold.
589 fn check_associated_type_bounds(fcx: &FnCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
590     let tcx = fcx.tcx;
591
592     let bounds = tcx.explicit_item_bounds(item.def_id);
593
594     debug!("check_associated_type_bounds: bounds={:?}", bounds);
595     let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
596         let normalized_bound = fcx.normalize_associated_types_in(span, bound);
597         traits::wf::predicate_obligations(
598             fcx,
599             fcx.param_env,
600             fcx.body_id,
601             normalized_bound,
602             bound_span,
603         )
604     });
605
606     for obligation in wf_obligations {
607         debug!("next obligation cause: {:?}", obligation.cause);
608         fcx.register_predicate(obligation);
609     }
610 }
611
612 fn check_item_fn(
613     tcx: TyCtxt<'_>,
614     item_id: hir::HirId,
615     ident: Ident,
616     span: Span,
617     decl: &hir::FnDecl<'_>,
618 ) {
619     for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
620         let def_id = fcx.tcx.hir().local_def_id(item_id);
621         let sig = fcx.tcx.fn_sig(def_id);
622         let sig = fcx.normalize_associated_types_in(span, sig);
623         let mut implied_bounds = vec![];
624         check_fn_or_method(
625             tcx,
626             fcx,
627             ident.span,
628             sig,
629             decl,
630             def_id.to_def_id(),
631             &mut implied_bounds,
632         );
633         implied_bounds
634     })
635 }
636
637 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
638     debug!("check_item_type: {:?}", item_id);
639
640     for_id(tcx, item_id, ty_span).with_fcx(|fcx, tcx| {
641         let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
642         let item_ty = fcx.normalize_associated_types_in(ty_span, ty);
643
644         let mut forbid_unsized = true;
645         if allow_foreign_ty {
646             let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
647             if let ty::Foreign(_) = tail.kind() {
648                 forbid_unsized = false;
649             }
650         }
651
652         fcx.register_wf_obligation(item_ty.into(), ty_span, ObligationCauseCode::MiscObligation);
653         if forbid_unsized {
654             fcx.register_bound(
655                 item_ty,
656                 fcx.tcx.require_lang_item(LangItem::Sized, None),
657                 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
658             );
659         }
660
661         // No implied bounds in a const, etc.
662         vec![]
663     });
664 }
665
666 fn check_impl<'tcx>(
667     tcx: TyCtxt<'tcx>,
668     item: &'tcx hir::Item<'tcx>,
669     ast_self_ty: &hir::Ty<'_>,
670     ast_trait_ref: &Option<hir::TraitRef<'_>>,
671 ) {
672     debug!("check_impl: {:?}", item);
673
674     for_item(tcx, item).with_fcx(|fcx, tcx| {
675         let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
676
677         match *ast_trait_ref {
678             Some(ref ast_trait_ref) => {
679                 // `#[rustc_reservation_impl]` impls are not real impls and
680                 // therefore don't need to be WF (the trait's `Self: Trait` predicate
681                 // won't hold).
682                 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
683                 let trait_ref =
684                     fcx.normalize_associated_types_in(ast_trait_ref.path.span, trait_ref);
685                 let obligations = traits::wf::trait_obligations(
686                     fcx,
687                     fcx.param_env,
688                     fcx.body_id,
689                     &trait_ref,
690                     ast_trait_ref.path.span,
691                     Some(item),
692                 );
693                 for obligation in obligations {
694                     fcx.register_predicate(obligation);
695                 }
696             }
697             None => {
698                 let self_ty = fcx.tcx.type_of(item_def_id);
699                 let self_ty = fcx.normalize_associated_types_in(item.span, self_ty);
700                 fcx.register_wf_obligation(
701                     self_ty.into(),
702                     ast_self_ty.span,
703                     ObligationCauseCode::MiscObligation,
704                 );
705             }
706         }
707
708         check_where_clauses(tcx, fcx, item.span, item_def_id.to_def_id(), None);
709
710         fcx.impl_implied_bounds(item_def_id.to_def_id(), item.span)
711     });
712 }
713
714 /// Checks where-clauses and inline bounds that are declared on `def_id`.
715 fn check_where_clauses<'tcx, 'fcx>(
716     tcx: TyCtxt<'tcx>,
717     fcx: &FnCtxt<'fcx, 'tcx>,
718     span: Span,
719     def_id: DefId,
720     return_ty: Option<(Ty<'tcx>, Span)>,
721 ) {
722     debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
723
724     let predicates = fcx.tcx.predicates_of(def_id);
725     let generics = tcx.generics_of(def_id);
726
727     let is_our_default = |def: &ty::GenericParamDef| match def.kind {
728         GenericParamDefKind::Type { has_default, .. } => {
729             has_default && def.index >= generics.parent_count as u32
730         }
731         _ => unreachable!(),
732     };
733
734     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
735     // For example, this forbids the declaration:
736     //
737     //     struct Foo<T = Vec<[u32]>> { .. }
738     //
739     // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
740     for param in &generics.params {
741         if let GenericParamDefKind::Type { .. } = param.kind {
742             if is_our_default(&param) {
743                 let ty = fcx.tcx.type_of(param.def_id);
744                 // Ignore dependent defaults -- that is, where the default of one type
745                 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
746                 // be sure if it will error or not as user might always specify the other.
747                 if !ty.needs_subst() {
748                     fcx.register_wf_obligation(
749                         ty.into(),
750                         fcx.tcx.def_span(param.def_id),
751                         ObligationCauseCode::MiscObligation,
752                     );
753                 }
754             }
755         }
756     }
757
758     // Check that trait predicates are WF when params are substituted by their defaults.
759     // We don't want to overly constrain the predicates that may be written but we want to
760     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
761     // Therefore we check if a predicate which contains a single type param
762     // with a concrete default is WF with that default substituted.
763     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
764     //
765     // First we build the defaulted substitution.
766     let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
767         match param.kind {
768             GenericParamDefKind::Lifetime => {
769                 // All regions are identity.
770                 fcx.tcx.mk_param_from_def(param)
771             }
772
773             GenericParamDefKind::Type { .. } => {
774                 // If the param has a default, ...
775                 if is_our_default(param) {
776                     let default_ty = fcx.tcx.type_of(param.def_id);
777                     // ... and it's not a dependent default, ...
778                     if !default_ty.needs_subst() {
779                         // ... then substitute it with the default.
780                         return default_ty.into();
781                     }
782                 }
783
784                 fcx.tcx.mk_param_from_def(param)
785             }
786
787             GenericParamDefKind::Const => {
788                 // FIXME(const_generics:defaults)
789                 fcx.tcx.mk_param_from_def(param)
790             }
791         }
792     });
793
794     // Now we build the substituted predicates.
795     let default_obligations = predicates
796         .predicates
797         .iter()
798         .flat_map(|&(pred, sp)| {
799             #[derive(Default)]
800             struct CountParams {
801                 params: FxHashSet<u32>,
802             }
803             impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
804                 type BreakTy = ();
805
806                 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
807                     if let ty::Param(param) = t.kind() {
808                         self.params.insert(param.index);
809                     }
810                     t.super_visit_with(self)
811                 }
812
813                 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
814                     ControlFlow::BREAK
815                 }
816
817                 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
818                     if let ty::ConstKind::Param(param) = c.val {
819                         self.params.insert(param.index);
820                     }
821                     c.super_visit_with(self)
822                 }
823             }
824             let mut param_count = CountParams::default();
825             let has_region = pred.visit_with(&mut param_count).is_break();
826             let substituted_pred = pred.subst(fcx.tcx, substs);
827             // Don't check non-defaulted params, dependent defaults (including lifetimes)
828             // or preds with multiple params.
829             if substituted_pred.has_param_types_or_consts()
830                 || param_count.params.len() > 1
831                 || has_region
832             {
833                 None
834             } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
835                 // Avoid duplication of predicates that contain no parameters, for example.
836                 None
837             } else {
838                 Some((substituted_pred, sp))
839             }
840         })
841         .map(|(pred, sp)| {
842             // Convert each of those into an obligation. So if you have
843             // something like `struct Foo<T: Copy = String>`, we would
844             // take that predicate `T: Copy`, substitute to `String: Copy`
845             // (actually that happens in the previous `flat_map` call),
846             // and then try to prove it (in this case, we'll fail).
847             //
848             // Note the subtle difference from how we handle `predicates`
849             // below: there, we are not trying to prove those predicates
850             // to be *true* but merely *well-formed*.
851             let pred = fcx.normalize_associated_types_in(sp, pred);
852             let cause =
853                 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
854             traits::Obligation::new(cause, fcx.param_env, pred)
855         });
856
857     let predicates = predicates.instantiate_identity(fcx.tcx);
858
859     if let Some((mut return_ty, span)) = return_ty {
860         if return_ty.has_infer_types_or_consts() {
861             fcx.select_obligations_where_possible(false, |_| {});
862             return_ty = fcx.resolve_vars_if_possible(return_ty);
863         }
864         check_opaque_types(tcx, fcx, def_id.expect_local(), span, return_ty);
865     }
866
867     let predicates = fcx.normalize_associated_types_in(span, predicates);
868
869     debug!("check_where_clauses: predicates={:?}", predicates.predicates);
870     assert_eq!(predicates.predicates.len(), predicates.spans.len());
871     let wf_obligations =
872         predicates.predicates.iter().zip(predicates.spans.iter()).flat_map(|(&p, &sp)| {
873             traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, sp)
874         });
875
876     for obligation in wf_obligations.chain(default_obligations) {
877         debug!("next obligation cause: {:?}", obligation.cause);
878         fcx.register_predicate(obligation);
879     }
880 }
881
882 fn check_fn_or_method<'fcx, 'tcx>(
883     tcx: TyCtxt<'tcx>,
884     fcx: &FnCtxt<'fcx, 'tcx>,
885     span: Span,
886     sig: ty::PolyFnSig<'tcx>,
887     hir_decl: &hir::FnDecl<'_>,
888     def_id: DefId,
889     implied_bounds: &mut Vec<Ty<'tcx>>,
890 ) {
891     let sig = fcx.normalize_associated_types_in(span, sig);
892     let sig = fcx.tcx.liberate_late_bound_regions(def_id, sig);
893
894     for (&input_ty, span) in sig.inputs().iter().zip(hir_decl.inputs.iter().map(|t| t.span)) {
895         fcx.register_wf_obligation(input_ty.into(), span, ObligationCauseCode::MiscObligation);
896     }
897     implied_bounds.extend(sig.inputs());
898
899     fcx.register_wf_obligation(
900         sig.output().into(),
901         hir_decl.output.span(),
902         ObligationCauseCode::ReturnType,
903     );
904
905     // FIXME(#25759) return types should not be implied bounds
906     implied_bounds.push(sig.output());
907
908     check_where_clauses(tcx, fcx, span, def_id, Some((sig.output(), hir_decl.output.span())));
909 }
910
911 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
912 /// laid for "higher-order pattern unification".
913 /// This ensures that inference is tractable.
914 /// In particular, definitions of opaque types can only use other generics as arguments,
915 /// and they cannot repeat an argument. Example:
916 ///
917 /// ```rust
918 /// type Foo<A, B> = impl Bar<A, B>;
919 ///
920 /// // Okay -- `Foo` is applied to two distinct, generic types.
921 /// fn a<T, U>() -> Foo<T, U> { .. }
922 ///
923 /// // Not okay -- `Foo` is applied to `T` twice.
924 /// fn b<T>() -> Foo<T, T> { .. }
925 ///
926 /// // Not okay -- `Foo` is applied to a non-generic type.
927 /// fn b<T>() -> Foo<T, u32> { .. }
928 /// ```
929 ///
930 fn check_opaque_types<'fcx, 'tcx>(
931     tcx: TyCtxt<'tcx>,
932     fcx: &FnCtxt<'fcx, 'tcx>,
933     fn_def_id: LocalDefId,
934     span: Span,
935     ty: Ty<'tcx>,
936 ) {
937     trace!("check_opaque_types(ty={:?})", ty);
938     ty.fold_with(&mut ty::fold::BottomUpFolder {
939         tcx: fcx.tcx,
940         ty_op: |ty| {
941             if let ty::Opaque(def_id, substs) = *ty.kind() {
942                 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
943                 let generics = tcx.generics_of(def_id);
944
945                 let opaque_hir_id = if let Some(local_id) = def_id.as_local() {
946                     tcx.hir().local_def_id_to_hir_id(local_id)
947                 } else {
948                     // Opaque types from other crates won't have defining uses in this crate.
949                     return ty;
950                 };
951                 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) =
952                     tcx.hir().expect_item(opaque_hir_id).kind
953                 {
954                     // No need to check return position impl trait (RPIT)
955                     // because for type and const parameters they are correct
956                     // by construction: we convert
957                     //
958                     // fn foo<P0..Pn>() -> impl Trait
959                     //
960                     // into
961                     //
962                     // type Foo<P0...Pn>
963                     // fn foo<P0..Pn>() -> Foo<P0...Pn>.
964                     //
965                     // For lifetime parameters we convert
966                     //
967                     // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
968                     //
969                     // into
970                     //
971                     // type foo::<'p0..'pn>::Foo<'q0..'qm>
972                     // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
973                     //
974                     // which would error here on all of the `'static` args.
975                     return ty;
976                 }
977                 if !may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
978                     return ty;
979                 }
980                 trace!("check_opaque_types: may define, generics={:#?}", generics);
981                 let mut seen_params: FxHashMap<_, Vec<_>> = FxHashMap::default();
982                 for (i, arg) in substs.iter().enumerate() {
983                     let arg_is_param = match arg.unpack() {
984                         GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)),
985
986                         GenericArgKind::Lifetime(region) => {
987                             if let ty::ReStatic = region {
988                                 tcx.sess
989                                     .struct_span_err(
990                                         span,
991                                         "non-defining opaque type use in defining scope",
992                                     )
993                                     .span_label(
994                                         tcx.def_span(generics.param_at(i, tcx).def_id),
995                                         "cannot use static lifetime; use a bound lifetime \
996                                                  instead or remove the lifetime parameter from the \
997                                                  opaque type",
998                                     )
999                                     .emit();
1000                                 continue;
1001                             }
1002
1003                             true
1004                         }
1005
1006                         GenericArgKind::Const(ct) => matches!(ct.val, ty::ConstKind::Param(_)),
1007                     };
1008
1009                     if arg_is_param {
1010                         seen_params.entry(arg).or_default().push(i);
1011                     } else {
1012                         // Prevent `fn foo() -> Foo<u32>` from being defining.
1013                         let opaque_param = generics.param_at(i, tcx);
1014                         tcx.sess
1015                             .struct_span_err(span, "non-defining opaque type use in defining scope")
1016                             .span_note(
1017                                 tcx.def_span(opaque_param.def_id),
1018                                 &format!(
1019                                     "used non-generic {} `{}` for generic parameter",
1020                                     opaque_param.kind.descr(),
1021                                     arg,
1022                                 ),
1023                             )
1024                             .emit();
1025                     }
1026                 } // for (arg, param)
1027
1028                 for (_, indices) in seen_params {
1029                     if indices.len() > 1 {
1030                         let descr = generics.param_at(indices[0], tcx).kind.descr();
1031                         let spans: Vec<_> = indices
1032                             .into_iter()
1033                             .map(|i| tcx.def_span(generics.param_at(i, tcx).def_id))
1034                             .collect();
1035                         tcx.sess
1036                             .struct_span_err(span, "non-defining opaque type use in defining scope")
1037                             .span_note(spans, &format!("{} used multiple times", descr))
1038                             .emit();
1039                     }
1040                 }
1041             } // if let Opaque
1042             ty
1043         },
1044         lt_op: |lt| lt,
1045         ct_op: |ct| ct,
1046     });
1047 }
1048
1049 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1050      `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1051      of the previous types except `Self`)";
1052
1053 fn check_method_receiver<'fcx, 'tcx>(
1054     fcx: &FnCtxt<'fcx, 'tcx>,
1055     fn_sig: &hir::FnSig<'_>,
1056     method: &ty::AssocItem,
1057     self_ty: Ty<'tcx>,
1058 ) {
1059     // Check that the method has a valid receiver type, given the type `Self`.
1060     debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
1061
1062     if !method.fn_has_self_parameter {
1063         return;
1064     }
1065
1066     let span = fn_sig.decl.inputs[0].span;
1067
1068     let sig = fcx.tcx.fn_sig(method.def_id);
1069     let sig = fcx.normalize_associated_types_in(span, sig);
1070     let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, sig);
1071
1072     debug!("check_method_receiver: sig={:?}", sig);
1073
1074     let self_ty = fcx.normalize_associated_types_in(span, self_ty);
1075     let self_ty = fcx.tcx.liberate_late_bound_regions(method.def_id, ty::Binder::bind(self_ty));
1076
1077     let receiver_ty = sig.inputs()[0];
1078
1079     let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
1080     let receiver_ty =
1081         fcx.tcx.liberate_late_bound_regions(method.def_id, ty::Binder::bind(receiver_ty));
1082
1083     if fcx.tcx.features().arbitrary_self_types {
1084         if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1085             // Report error; `arbitrary_self_types` was enabled.
1086             e0307(fcx, span, receiver_ty);
1087         }
1088     } else {
1089         if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1090             if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1091                 // Report error; would have worked with `arbitrary_self_types`.
1092                 feature_err(
1093                     &fcx.tcx.sess.parse_sess,
1094                     sym::arbitrary_self_types,
1095                     span,
1096                     &format!(
1097                         "`{}` cannot be used as the type of `self` without \
1098                          the `arbitrary_self_types` feature",
1099                         receiver_ty,
1100                     ),
1101                 )
1102                 .help(HELP_FOR_SELF_TYPE)
1103                 .emit();
1104             } else {
1105                 // Report error; would not have worked with `arbitrary_self_types`.
1106                 e0307(fcx, span, receiver_ty);
1107             }
1108         }
1109     }
1110 }
1111
1112 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1113     struct_span_err!(
1114         fcx.tcx.sess.diagnostic(),
1115         span,
1116         E0307,
1117         "invalid `self` parameter type: {}",
1118         receiver_ty,
1119     )
1120     .note("type of `self` must be `Self` or a type that dereferences to it")
1121     .help(HELP_FOR_SELF_TYPE)
1122     .emit();
1123 }
1124
1125 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1126 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1127 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1128 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1129 /// `Deref<Target = self_ty>`.
1130 ///
1131 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1132 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1133 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1134 fn receiver_is_valid<'fcx, 'tcx>(
1135     fcx: &FnCtxt<'fcx, 'tcx>,
1136     span: Span,
1137     receiver_ty: Ty<'tcx>,
1138     self_ty: Ty<'tcx>,
1139     arbitrary_self_types_enabled: bool,
1140 ) -> bool {
1141     let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1142
1143     let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1144
1145     // `self: Self` is always valid.
1146     if can_eq_self(receiver_ty) {
1147         if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1148             err.emit();
1149         }
1150         return true;
1151     }
1152
1153     let mut autoderef = fcx.autoderef(span, receiver_ty);
1154
1155     // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1156     if arbitrary_self_types_enabled {
1157         autoderef = autoderef.include_raw_pointers();
1158     }
1159
1160     // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1161     autoderef.next();
1162
1163     let receiver_trait_def_id = fcx.tcx.require_lang_item(LangItem::Receiver, None);
1164
1165     // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1166     loop {
1167         if let Some((potential_self_ty, _)) = autoderef.next() {
1168             debug!(
1169                 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1170                 potential_self_ty, self_ty
1171             );
1172
1173             if can_eq_self(potential_self_ty) {
1174                 fcx.register_predicates(autoderef.into_obligations());
1175
1176                 if let Some(mut err) =
1177                     fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1178                 {
1179                     err.emit();
1180                 }
1181
1182                 break;
1183             } else {
1184                 // Without `feature(arbitrary_self_types)`, we require that each step in the
1185                 // deref chain implement `receiver`
1186                 if !arbitrary_self_types_enabled
1187                     && !receiver_is_implemented(
1188                         fcx,
1189                         receiver_trait_def_id,
1190                         cause.clone(),
1191                         potential_self_ty,
1192                     )
1193                 {
1194                     return false;
1195                 }
1196             }
1197         } else {
1198             debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1199             // If he receiver already has errors reported due to it, consider it valid to avoid
1200             // unnecessary errors (#58712).
1201             return receiver_ty.references_error();
1202         }
1203     }
1204
1205     // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1206     if !arbitrary_self_types_enabled
1207         && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1208     {
1209         return false;
1210     }
1211
1212     true
1213 }
1214
1215 fn receiver_is_implemented(
1216     fcx: &FnCtxt<'_, 'tcx>,
1217     receiver_trait_def_id: DefId,
1218     cause: ObligationCause<'tcx>,
1219     receiver_ty: Ty<'tcx>,
1220 ) -> bool {
1221     let trait_ref = ty::TraitRef {
1222         def_id: receiver_trait_def_id,
1223         substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1224     };
1225
1226     let obligation = traits::Obligation::new(
1227         cause,
1228         fcx.param_env,
1229         trait_ref.without_const().to_predicate(fcx.tcx),
1230     );
1231
1232     if fcx.predicate_must_hold_modulo_regions(&obligation) {
1233         true
1234     } else {
1235         debug!(
1236             "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1237             receiver_ty
1238         );
1239         false
1240     }
1241 }
1242
1243 fn check_variances_for_type_defn<'tcx>(
1244     tcx: TyCtxt<'tcx>,
1245     item: &hir::Item<'tcx>,
1246     hir_generics: &hir::Generics<'_>,
1247 ) {
1248     let item_def_id = tcx.hir().local_def_id(item.hir_id);
1249     let ty = tcx.type_of(item_def_id);
1250     if tcx.has_error_field(ty) {
1251         return;
1252     }
1253
1254     let ty_predicates = tcx.predicates_of(item_def_id);
1255     assert_eq!(ty_predicates.parent, None);
1256     let variances = tcx.variances_of(item_def_id);
1257
1258     let mut constrained_parameters: FxHashSet<_> = variances
1259         .iter()
1260         .enumerate()
1261         .filter(|&(_, &variance)| variance != ty::Bivariant)
1262         .map(|(index, _)| Parameter(index as u32))
1263         .collect();
1264
1265     identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1266
1267     for (index, _) in variances.iter().enumerate() {
1268         if constrained_parameters.contains(&Parameter(index as u32)) {
1269             continue;
1270         }
1271
1272         let param = &hir_generics.params[index];
1273
1274         match param.name {
1275             hir::ParamName::Error => {}
1276             _ => report_bivariance(tcx, param.span, param.name.ident().name),
1277         }
1278     }
1279 }
1280
1281 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) {
1282     let mut err = error_392(tcx, span, param_name);
1283
1284     let suggested_marker_id = tcx.lang_items().phantom_data();
1285     // Help is available only in presence of lang items.
1286     let msg = if let Some(def_id) = suggested_marker_id {
1287         format!(
1288             "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1289             param_name,
1290             tcx.def_path_str(def_id),
1291         )
1292     } else {
1293         format!("consider removing `{}` or referring to it in a field", param_name)
1294     };
1295     err.help(&msg);
1296     err.emit();
1297 }
1298
1299 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1300 /// aren't true.
1301 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1302     let empty_env = ty::ParamEnv::empty();
1303
1304     let def_id = fcx.tcx.hir().local_def_id(id);
1305     let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p);
1306     // Check elaborated bounds.
1307     let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1308
1309     for obligation in implied_obligations {
1310         let pred = obligation.predicate;
1311         // Match the existing behavior.
1312         if pred.is_global() && !pred.has_late_bound_regions() {
1313             let pred = fcx.normalize_associated_types_in(span, pred);
1314             let obligation = traits::Obligation::new(
1315                 traits::ObligationCause::new(span, id, traits::TrivialBound),
1316                 empty_env,
1317                 pred,
1318             );
1319             fcx.register_predicate(obligation);
1320         }
1321     }
1322
1323     fcx.select_all_obligations_or_error();
1324 }
1325
1326 #[derive(Clone, Copy)]
1327 pub struct CheckTypeWellFormedVisitor<'tcx> {
1328     tcx: TyCtxt<'tcx>,
1329 }
1330
1331 impl CheckTypeWellFormedVisitor<'tcx> {
1332     pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1333         CheckTypeWellFormedVisitor { tcx }
1334     }
1335 }
1336
1337 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1338     fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1339         Visitor::visit_item(&mut self.clone(), i);
1340     }
1341
1342     fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1343         Visitor::visit_trait_item(&mut self.clone(), trait_item);
1344     }
1345
1346     fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1347         Visitor::visit_impl_item(&mut self.clone(), impl_item);
1348     }
1349
1350     fn visit_foreign_item(&self, foreign_item: &'tcx hir::ForeignItem<'tcx>) {
1351         Visitor::visit_foreign_item(&mut self.clone(), foreign_item)
1352     }
1353 }
1354
1355 impl Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1356     type Map = hir_map::Map<'tcx>;
1357
1358     fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
1359         hir_visit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
1360     }
1361
1362     fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
1363         debug!("visit_item: {:?}", i);
1364         let def_id = self.tcx.hir().local_def_id(i.hir_id);
1365         self.tcx.ensure().check_item_well_formed(def_id);
1366         hir_visit::walk_item(self, i);
1367     }
1368
1369     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1370         debug!("visit_trait_item: {:?}", trait_item);
1371         let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1372         self.tcx.ensure().check_trait_item_well_formed(def_id);
1373         hir_visit::walk_trait_item(self, trait_item);
1374     }
1375
1376     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1377         debug!("visit_impl_item: {:?}", impl_item);
1378         let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1379         self.tcx.ensure().check_impl_item_well_formed(def_id);
1380         hir_visit::walk_impl_item(self, impl_item);
1381     }
1382
1383     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
1384         check_param_wf(self.tcx, p);
1385         hir_visit::walk_generic_param(self, p);
1386     }
1387 }
1388
1389 ///////////////////////////////////////////////////////////////////////////
1390 // ADT
1391
1392 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1393 struct AdtVariant<'tcx> {
1394     /// Types of fields in the variant, that must be well-formed.
1395     fields: Vec<AdtField<'tcx>>,
1396
1397     /// Explicit discriminant of this variant (e.g. `A = 123`),
1398     /// that must evaluate to a constant value.
1399     explicit_discr: Option<LocalDefId>,
1400 }
1401
1402 struct AdtField<'tcx> {
1403     ty: Ty<'tcx>,
1404     span: Span,
1405 }
1406
1407 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1408     // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1409     fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1410         let fields = struct_def
1411             .fields()
1412             .iter()
1413             .map(|field| {
1414                 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1415                 let field_ty = self.normalize_associated_types_in(field.ty.span, field_ty);
1416                 let field_ty = self.resolve_vars_if_possible(field_ty);
1417                 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1418                 AdtField { ty: field_ty, span: field.ty.span }
1419             })
1420             .collect();
1421         AdtVariant { fields, explicit_discr: None }
1422     }
1423
1424     fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1425         enum_def
1426             .variants
1427             .iter()
1428             .map(|variant| AdtVariant {
1429                 fields: self.non_enum_variant(&variant.data).fields,
1430                 explicit_discr: variant
1431                     .disr_expr
1432                     .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
1433             })
1434             .collect()
1435     }
1436
1437     pub(super) fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1438         match self.tcx.impl_trait_ref(impl_def_id) {
1439             Some(trait_ref) => {
1440                 // Trait impl: take implied bounds from all types that
1441                 // appear in the trait reference.
1442                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1443                 trait_ref.substs.types().collect()
1444             }
1445
1446             None => {
1447                 // Inherent impl: take implied bounds from the `self` type.
1448                 let self_ty = self.tcx.type_of(impl_def_id);
1449                 let self_ty = self.normalize_associated_types_in(span, self_ty);
1450                 vec![self_ty]
1451             }
1452         }
1453     }
1454 }
1455
1456 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) -> DiagnosticBuilder<'_> {
1457     let mut err =
1458         struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1459     err.span_label(span, "unused parameter");
1460     err
1461 }