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