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