]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
Auto merge of #50275 - kennytm:rollup, r=kennytm
[rust.git] / src / librustc_typeck / check / wfcheck.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use check::{Inherited, FnCtxt};
12 use constrained_type_params::{identify_constrained_type_params, Parameter};
13
14 use hir::def_id::DefId;
15 use rustc::traits::{self, ObligationCauseCode};
16 use rustc::ty::{self, Lift, Ty, TyCtxt};
17 use rustc::ty::util::ExplicitSelf;
18 use rustc::util::nodemap::{FxHashSet, FxHashMap};
19 use rustc::middle::lang_items;
20
21 use syntax::ast;
22 use syntax::feature_gate::{self, GateIssue};
23 use syntax_pos::Span;
24 use errors::{DiagnosticBuilder, DiagnosticId};
25
26 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
27 use rustc::hir;
28
29 /// Helper type of a temporary returned by .for_item(...).
30 /// Necessary because we can't write the following bound:
31 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>).
32 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
33     inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
34     id: ast::NodeId,
35     span: Span,
36     param_env: ty::ParamEnv<'tcx>,
37 }
38
39 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
40     fn with_fcx<F>(&'tcx mut self, f: F) where
41         F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
42                          TyCtxt<'b, 'gcx, 'gcx>) -> Vec<Ty<'tcx>>
43     {
44         let id = self.id;
45         let span = self.span;
46         let param_env = self.param_env;
47         self.inherited.enter(|inh| {
48             let fcx = FnCtxt::new(&inh, param_env, id);
49             let wf_tys = f(&fcx, fcx.tcx.global_tcx());
50             fcx.select_all_obligations_or_error();
51             fcx.regionck_item(id, span, &wf_tys);
52         });
53     }
54 }
55
56 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
57 /// well-formed, meaning that they do not require any constraints not declared in the struct
58 /// definition itself. For example, this definition would be illegal:
59 ///
60 ///     struct Ref<'a, T> { x: &'a T }
61 ///
62 /// because the type did not declare that `T:'a`.
63 ///
64 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
65 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
66 /// the types first.
67 pub fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
68     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
69     let item = tcx.hir.expect_item(node_id);
70
71     debug!("check_item_well_formed(it.id={}, it.name={})",
72             item.id,
73             tcx.item_path_str(def_id));
74
75     match item.node {
76         // Right now we check that every default trait implementation
77         // has an implementation of itself. Basically, a case like:
78         //
79         // `impl Trait for T {}`
80         //
81         // has a requirement of `T: Trait` which was required for default
82         // method implementations. Although this could be improved now that
83         // there's a better infrastructure in place for this, it's being left
84         // for a follow-up work.
85         //
86         // Since there's such a requirement, we need to check *just* positive
87         // implementations, otherwise things like:
88         //
89         // impl !Send for T {}
90         //
91         // won't be allowed unless there's an *explicit* implementation of `Send`
92         // for `T`
93         hir::ItemImpl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
94             let is_auto = tcx.impl_trait_ref(tcx.hir.local_def_id(item.id))
95                                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
96             if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
97                 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
98             }
99             if polarity == hir::ImplPolarity::Positive {
100                 check_impl(tcx, item, self_ty, trait_ref);
101             } else {
102                 // FIXME(#27579) what amount of WF checking do we need for neg impls?
103                 if trait_ref.is_some() && !is_auto {
104                     span_err!(tcx.sess, item.span, E0192,
105                                 "negative impls are only allowed for \
106                                 auto traits (e.g., `Send` and `Sync`)")
107                 }
108             }
109         }
110         hir::ItemFn(..) => {
111             check_item_fn(tcx, item);
112         }
113         hir::ItemStatic(..) => {
114             check_item_type(tcx, item);
115         }
116         hir::ItemConst(..) => {
117             check_item_type(tcx, item);
118         }
119         hir::ItemStruct(ref struct_def, ref ast_generics) => {
120             check_type_defn(tcx, item, false, |fcx| {
121                 vec![fcx.non_enum_variant(struct_def)]
122             });
123
124             check_variances_for_type_defn(tcx, item, ast_generics);
125         }
126         hir::ItemUnion(ref struct_def, ref ast_generics) => {
127             check_type_defn(tcx, item, true, |fcx| {
128                 vec![fcx.non_enum_variant(struct_def)]
129             });
130
131             check_variances_for_type_defn(tcx, item, ast_generics);
132         }
133         hir::ItemEnum(ref enum_def, ref ast_generics) => {
134             check_type_defn(tcx, item, true, |fcx| {
135                 fcx.enum_variants(enum_def)
136             });
137
138             check_variances_for_type_defn(tcx, item, ast_generics);
139         }
140         hir::ItemTrait(..) => {
141             check_trait(tcx, item);
142         }
143         _ => {}
144     }
145 }
146
147 pub fn check_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
148     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
149     let trait_item = tcx.hir.expect_trait_item(node_id);
150
151     let method_sig = match trait_item.node {
152         hir::TraitItemKind::Method(ref sig, _) => Some(sig),
153         _ => None
154     };
155     check_associated_item(tcx, trait_item.id, trait_item.span, method_sig);
156 }
157
158 pub fn check_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
159     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
160     let impl_item = tcx.hir.expect_impl_item(node_id);
161
162     let method_sig = match impl_item.node {
163         hir::ImplItemKind::Method(ref sig, _) => Some(sig),
164         _ => None
165     };
166     check_associated_item(tcx, impl_item.id, impl_item.span, method_sig);
167 }
168
169 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
170                             item_id: ast::NodeId,
171                             span: Span,
172                             sig_if_method: Option<&hir::MethodSig>) {
173     let code = ObligationCauseCode::MiscObligation;
174     for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
175         let item = fcx.tcx.associated_item(fcx.tcx.hir.local_def_id(item_id));
176
177         let (mut implied_bounds, self_ty) = match item.container {
178             ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
179             ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
180                                             fcx.tcx.type_of(def_id))
181         };
182
183         match item.kind {
184             ty::AssociatedKind::Const => {
185                 let ty = fcx.tcx.type_of(item.def_id);
186                 let ty = fcx.normalize_associated_types_in(span, &ty);
187                 fcx.register_wf_obligation(ty, span, code.clone());
188             }
189             ty::AssociatedKind::Method => {
190                 reject_shadowing_type_parameters(fcx.tcx, item.def_id);
191                 let sig = fcx.tcx.fn_sig(item.def_id);
192                 let sig = fcx.normalize_associated_types_in(span, &sig);
193                 check_fn_or_method(tcx, fcx, span, sig,
194                                         item.def_id, &mut implied_bounds);
195                 let sig_if_method = sig_if_method.expect("bad signature for method");
196                 check_method_receiver(fcx, sig_if_method, &item, self_ty);
197             }
198             ty::AssociatedKind::Type => {
199                 if item.defaultness.has_value() {
200                     let ty = fcx.tcx.type_of(item.def_id);
201                     let ty = fcx.normalize_associated_types_in(span, &ty);
202                     fcx.register_wf_obligation(ty, span, code.clone());
203                 }
204             }
205         }
206
207         implied_bounds
208     })
209 }
210
211 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
212                     -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
213     for_id(tcx, item.id, item.span)
214 }
215
216 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId, span: Span)
217                 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
218     let def_id = tcx.hir.local_def_id(id);
219     CheckWfFcxBuilder {
220         inherited: Inherited::build(tcx, def_id),
221         id,
222         span,
223         param_env: tcx.param_env(def_id),
224     }
225 }
226
227 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
228 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
229                                 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
230     where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
231 {
232     for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
233         let variants = lookup_fields(fcx);
234         let def_id = fcx.tcx.hir.local_def_id(item.id);
235         let packed = fcx.tcx.adt_def(def_id).repr.packed();
236
237         for variant in &variants {
238             // For DST, or when drop needs to copy things around, all
239             // intermediate types must be sized.
240             let needs_drop_copy = || {
241                 packed && {
242                     let ty = variant.fields.last().unwrap().ty;
243                     let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
244                         .unwrap_or_else(|| {
245                             span_bug!(item.span, "inference variables in {:?}", ty)
246                         });
247                     ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
248                 }
249             };
250             let unsized_len = if
251                 all_sized ||
252                 variant.fields.is_empty() ||
253                 needs_drop_copy()
254             {
255                 0
256             } else {
257                 1
258             };
259             for field in &variant.fields[..variant.fields.len() - unsized_len] {
260                 fcx.register_bound(
261                     field.ty,
262                     fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
263                     traits::ObligationCause::new(field.span,
264                                                     fcx.body_id,
265                                                     traits::FieldSized(match item.node.adt_kind() {
266                                                     Some(i) => i,
267                                                     None => bug!(),
268                                                     })));
269             }
270
271             // All field types must be well-formed.
272             for field in &variant.fields {
273                 fcx.register_wf_obligation(field.ty, field.span,
274                     ObligationCauseCode::MiscObligation)
275             }
276         }
277
278         check_where_clauses(tcx, fcx, item.span, def_id);
279
280         vec![] // no implied bounds in a struct def'n
281     });
282 }
283
284 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
285     let trait_def_id = tcx.hir.local_def_id(item.id);
286     for_item(tcx, item).with_fcx(|fcx, _| {
287         check_where_clauses(tcx, fcx, item.span, trait_def_id);
288         vec![]
289     });
290 }
291
292 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
293     for_item(tcx, item).with_fcx(|fcx, tcx| {
294         let def_id = fcx.tcx.hir.local_def_id(item.id);
295         let sig = fcx.tcx.fn_sig(def_id);
296         let sig = fcx.normalize_associated_types_in(item.span, &sig);
297         let mut implied_bounds = vec![];
298         check_fn_or_method(tcx, fcx, item.span, sig,
299                                 def_id, &mut implied_bounds);
300         implied_bounds
301     })
302 }
303
304 fn check_item_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
305                     item: &hir::Item)
306 {
307     debug!("check_item_type: {:?}", item);
308
309     for_item(tcx, item).with_fcx(|fcx, _this| {
310         let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
311         let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
312
313         fcx.register_wf_obligation(item_ty, item.span, ObligationCauseCode::MiscObligation);
314
315         vec![] // no implied bounds in a const etc
316     });
317 }
318
319 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
320                 item: &hir::Item,
321                 ast_self_ty: &hir::Ty,
322                 ast_trait_ref: &Option<hir::TraitRef>)
323 {
324     debug!("check_impl: {:?}", item);
325
326     for_item(tcx, item).with_fcx(|fcx, tcx| {
327         let item_def_id = fcx.tcx.hir.local_def_id(item.id);
328
329         match *ast_trait_ref {
330             Some(ref ast_trait_ref) => {
331                 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
332                 let trait_ref =
333                     fcx.normalize_associated_types_in(
334                         ast_trait_ref.path.span, &trait_ref);
335                 let obligations =
336                     ty::wf::trait_obligations(fcx,
337                                                 fcx.param_env,
338                                                 fcx.body_id,
339                                                 &trait_ref,
340                                                 ast_trait_ref.path.span);
341                 for obligation in obligations {
342                     fcx.register_predicate(obligation);
343                 }
344             }
345             None => {
346                 let self_ty = fcx.tcx.type_of(item_def_id);
347                 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
348                 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
349                     ObligationCauseCode::MiscObligation);
350             }
351         }
352
353         check_where_clauses(tcx, fcx, item.span, item_def_id);
354
355         fcx.impl_implied_bounds(item_def_id, item.span)
356     });
357 }
358
359 /// Checks where clauses and inline bounds that are declared on def_id.
360 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
361                                     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
362                                     span: Span,
363                                     def_id: DefId) {
364     use ty::subst::Subst;
365     use rustc::ty::TypeFoldable;
366
367     let mut predicates = fcx.tcx.predicates_of(def_id);
368     let mut substituted_predicates = Vec::new();
369
370     let generics = tcx.generics_of(def_id);
371     let is_our_default = |def: &ty::TypeParameterDef|
372                             def.has_default && def.index >= generics.parent_count() as u32;
373
374     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
375     // For example this forbids the declaration:
376     // struct Foo<T = Vec<[u32]>> { .. }
377     // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
378     for d in generics.types.iter().cloned().filter(is_our_default).map(|p| p.def_id) {
379         let ty = fcx.tcx.type_of(d);
380         // ignore dependent defaults -- that is, where the default of one type
381         // parameter includes another (e.g., <T, U = T>). In those cases, we can't
382         // be sure if it will error or not as user might always specify the other.
383         if !ty.needs_subst() {
384             fcx.register_wf_obligation(ty, fcx.tcx.def_span(d),
385                 ObligationCauseCode::MiscObligation);
386         }
387     }
388
389     // Check that trait predicates are WF when params are substituted by their defaults.
390     // We don't want to overly constrain the predicates that may be written but we want to
391     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
392     // Therefore we check if a predicate which contains a single type param
393     // with a concrete default is WF with that default substituted.
394     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
395     //
396     // First we build the defaulted substitution.
397     let substs = ty::subst::Substs::for_item(fcx.tcx, def_id, |def, _| {
398             // All regions are identity.
399             fcx.tcx.mk_region(ty::ReEarlyBound(def.to_early_bound_region_data()))
400         }, |def, _| {
401             // If the param has a default,
402             if is_our_default(def) {
403                 let default_ty = fcx.tcx.type_of(def.def_id);
404                 // and it's not a dependent default
405                 if !default_ty.needs_subst() {
406                     // then substitute with the default.
407                     return default_ty;
408                 }
409             }
410             // Mark unwanted params as err.
411             fcx.tcx.types.err
412         });
413     // Now we build the substituted predicates.
414     for &pred in predicates.predicates.iter() {
415         struct CountParams { params: FxHashSet<u32> }
416         impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
417             fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
418                 match t.sty {
419                     ty::TyParam(p) => {
420                         self.params.insert(p.idx);
421                         t.super_visit_with(self)
422                     }
423                     _ => t.super_visit_with(self)
424                 }
425             }
426
427             fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
428                 true
429             }
430         }
431         let mut param_count = CountParams { params: FxHashSet() };
432         let has_region = pred.visit_with(&mut param_count);
433         let substituted_pred = pred.subst(fcx.tcx, substs);
434         // Don't check non-defaulted params, dependent defaults (including lifetimes)
435         // or preds with multiple params.
436         if substituted_pred.references_error() || param_count.params.len() > 1
437             || has_region {
438             continue;
439         }
440         // Avoid duplication of predicates that contain no parameters, for example.
441         if !predicates.predicates.contains(&substituted_pred) {
442             substituted_predicates.push(substituted_pred);
443         }
444     }
445
446     predicates.predicates.extend(substituted_predicates);
447     let predicates = predicates.instantiate_identity(fcx.tcx);
448     let predicates = fcx.normalize_associated_types_in(span, &predicates);
449
450     let obligations =
451         predicates.predicates
452                     .iter()
453                     .flat_map(|p| ty::wf::predicate_obligations(fcx,
454                                                                 fcx.param_env,
455                                                                 fcx.body_id,
456                                                                 p,
457                                                                 span));
458
459     for obligation in obligations {
460         fcx.register_predicate(obligation);
461     }
462 }
463
464 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
465                                     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
466                                     span: Span,
467                                     sig: ty::PolyFnSig<'tcx>,
468                                     def_id: DefId,
469                                     implied_bounds: &mut Vec<Ty<'tcx>>)
470 {
471     let sig = fcx.normalize_associated_types_in(span, &sig);
472     let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
473
474     for input_ty in sig.inputs() {
475         fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
476     }
477     implied_bounds.extend(sig.inputs());
478
479     fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
480
481     // FIXME(#25759) return types should not be implied bounds
482     implied_bounds.push(sig.output());
483
484     check_where_clauses(tcx, fcx, span, def_id);
485 }
486
487 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
488                                            method_sig: &hir::MethodSig,
489                                            method: &ty::AssociatedItem,
490                                            self_ty: Ty<'tcx>)
491 {
492     // check that the method has a valid receiver type, given the type `Self`
493     debug!("check_method_receiver({:?}, self_ty={:?})",
494             method, self_ty);
495
496     if !method.method_has_self_argument {
497         return;
498     }
499
500     let span = method_sig.decl.inputs[0].span;
501
502     let sig = fcx.tcx.fn_sig(method.def_id);
503     let sig = fcx.normalize_associated_types_in(span, &sig);
504     let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
505
506     debug!("check_method_receiver: sig={:?}", sig);
507
508     let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
509     let self_ty = fcx.tcx.liberate_late_bound_regions(
510         method.def_id,
511         &ty::Binder::bind(self_ty)
512     );
513
514     let self_arg_ty = sig.inputs()[0];
515
516     let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
517     let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
518     let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
519         method.def_id,
520         &ty::Binder::bind(self_arg_ty)
521     );
522
523     let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
524
525     loop {
526         if let Some((potential_self_ty, _)) = autoderef.next() {
527             debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
528                 potential_self_ty, self_ty);
529
530             if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
531                 autoderef.finalize();
532                 if let Some(mut err) = fcx.demand_eqtype_with_origin(
533                     &cause, self_ty, potential_self_ty) {
534                     err.emit();
535                 }
536                 break
537             }
538         } else {
539             fcx.tcx.sess.diagnostic().mut_span_err(
540                 span, &format!("invalid `self` type: {:?}", self_arg_ty))
541             .note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty))
542             .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
543             .code(DiagnosticId::Error("E0307".into()))
544             .emit();
545             return
546         }
547     }
548
549     let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
550     let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
551
552     if !fcx.tcx.features().arbitrary_self_types {
553         match self_kind {
554             ExplicitSelf::ByValue |
555             ExplicitSelf::ByReference(_, _) |
556             ExplicitSelf::ByBox => (),
557
558             ExplicitSelf::ByRawPointer(_) => {
559                 feature_gate::feature_err(
560                     &fcx.tcx.sess.parse_sess,
561                     "arbitrary_self_types",
562                     span,
563                     GateIssue::Language,
564                     "raw pointer `self` is unstable")
565                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
566                 .emit();
567             }
568
569             ExplicitSelf::Other => {
570                 feature_gate::feature_err(
571                     &fcx.tcx.sess.parse_sess,
572                     "arbitrary_self_types",
573                     span,
574                     GateIssue::Language,"arbitrary `self` types are unstable")
575                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
576                 .emit();
577             }
578         }
579     }
580 }
581
582 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
583                                     item: &hir::Item,
584                                     ast_generics: &hir::Generics)
585 {
586     let item_def_id = tcx.hir.local_def_id(item.id);
587     let ty = tcx.type_of(item_def_id);
588     if tcx.has_error_field(ty) {
589         return;
590     }
591
592     let ty_predicates = tcx.predicates_of(item_def_id);
593     assert_eq!(ty_predicates.parent, None);
594     let variances = tcx.variances_of(item_def_id);
595
596     let mut constrained_parameters: FxHashSet<_> =
597         variances.iter().enumerate()
598                     .filter(|&(_, &variance)| variance != ty::Bivariant)
599                     .map(|(index, _)| Parameter(index as u32))
600                     .collect();
601
602     identify_constrained_type_params(tcx,
603                                         ty_predicates.predicates.as_slice(),
604                                         None,
605                                         &mut constrained_parameters);
606
607     for (index, _) in variances.iter().enumerate() {
608         if constrained_parameters.contains(&Parameter(index as u32)) {
609             continue;
610         }
611
612         let (span, name) = match ast_generics.params[index] {
613             hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()),
614             hir::GenericParam::Type(ref tp) => (tp.span, tp.name),
615         };
616         report_bivariance(tcx, span, name);
617     }
618 }
619
620 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
621                         span: Span,
622                         param_name: ast::Name)
623 {
624     let mut err = error_392(tcx, span, param_name);
625
626     let suggested_marker_id = tcx.lang_items().phantom_data();
627     match suggested_marker_id {
628         Some(def_id) => {
629             err.help(
630                 &format!("consider removing `{}` or using a marker such as `{}`",
631                             param_name,
632                             tcx.item_path_str(def_id)));
633         }
634         None => {
635             // no lang items, no help!
636         }
637     }
638     err.emit();
639 }
640
641 fn reject_shadowing_type_parameters(tcx: TyCtxt, def_id: DefId) {
642     let generics = tcx.generics_of(def_id);
643     let parent = tcx.generics_of(generics.parent.unwrap());
644     let impl_params: FxHashMap<_, _> = parent.types
645                                        .iter()
646                                        .map(|tp| (tp.name, tp.def_id))
647                                        .collect();
648
649     for method_param in &generics.types {
650         if impl_params.contains_key(&method_param.name) {
651             // Tighten up the span to focus on only the shadowing type
652             let type_span = tcx.def_span(method_param.def_id);
653
654             // The expectation here is that the original trait declaration is
655             // local so it should be okay to just unwrap everything.
656             let trait_def_id = impl_params[&method_param.name];
657             let trait_decl_span = tcx.def_span(trait_def_id);
658             error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
659         }
660     }
661 }
662
663 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
664     tcx: TyCtxt<'a, 'tcx, 'tcx>,
665 }
666
667 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
668     pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
669                -> CheckTypeWellFormedVisitor<'a, 'gcx> {
670         CheckTypeWellFormedVisitor {
671             tcx,
672         }
673     }
674 }
675
676 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
677     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
678         NestedVisitorMap::None
679     }
680
681     fn visit_item(&mut self, i: &hir::Item) {
682         debug!("visit_item: {:?}", i);
683         let def_id = self.tcx.hir.local_def_id(i.id);
684         ty::maps::queries::check_item_well_formed::ensure(self.tcx, def_id);
685         intravisit::walk_item(self, i);
686     }
687
688     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
689         debug!("visit_trait_item: {:?}", trait_item);
690         let def_id = self.tcx.hir.local_def_id(trait_item.id);
691         ty::maps::queries::check_trait_item_well_formed::ensure(self.tcx, def_id);
692         intravisit::walk_trait_item(self, trait_item)
693     }
694
695     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
696         debug!("visit_impl_item: {:?}", impl_item);
697         let def_id = self.tcx.hir.local_def_id(impl_item.id);
698         ty::maps::queries::check_impl_item_well_formed::ensure(self.tcx, def_id);
699         intravisit::walk_impl_item(self, impl_item)
700     }
701 }
702
703 ///////////////////////////////////////////////////////////////////////////
704 // ADT
705
706 struct AdtVariant<'tcx> {
707     fields: Vec<AdtField<'tcx>>,
708 }
709
710 struct AdtField<'tcx> {
711     ty: Ty<'tcx>,
712     span: Span,
713 }
714
715 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
716     fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
717         let fields =
718             struct_def.fields().iter()
719             .map(|field| {
720                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
721                 let field_ty = self.normalize_associated_types_in(field.span,
722                                                                   &field_ty);
723                 AdtField { ty: field_ty, span: field.span }
724             })
725             .collect();
726         AdtVariant { fields: fields }
727     }
728
729     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
730         enum_def.variants.iter()
731             .map(|variant| self.non_enum_variant(&variant.node.data))
732             .collect()
733     }
734
735     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
736         match self.tcx.impl_trait_ref(impl_def_id) {
737             Some(ref trait_ref) => {
738                 // Trait impl: take implied bounds from all types that
739                 // appear in the trait reference.
740                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
741                 trait_ref.substs.types().collect()
742             }
743
744             None => {
745                 // Inherent impl: take implied bounds from the self type.
746                 let self_ty = self.tcx.type_of(impl_def_id);
747                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
748                 vec![self_ty]
749             }
750         }
751     }
752 }
753
754 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
755                        -> DiagnosticBuilder<'tcx> {
756     let mut err = struct_span_err!(tcx.sess, span, E0392,
757                   "parameter `{}` is never used", param_name);
758     err.span_label(span, "unused type parameter");
759     err
760 }
761
762 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: &str) {
763     struct_span_err!(tcx.sess, span, E0194,
764               "type parameter `{}` shadows another type parameter of the same name",
765               name)
766         .span_label(span, "shadows another type parameter")
767         .span_label(trait_decl_span, format!("first `{}` declared here", name))
768         .emit();
769 }