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