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