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