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