]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
Auto merge of #49313 - sgrif:sg-revert-stuff, r=nikomatsakis
[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         let mut param_count = CountParams { params: FxHashSet() };
428         pred.visit_with(&mut param_count);
429         let substituted_pred = pred.subst(fcx.tcx, substs);
430         // Don't check non-defaulted params, dependent defaults or preds with multiple params.
431         if substituted_pred.references_error() || param_count.params.len() > 1 {
432             continue;
433         }
434         // Avoid duplication of predicates that contain no parameters, for example.
435         if !predicates.predicates.contains(&substituted_pred) {
436             substituted_predicates.push(substituted_pred);
437         }
438     }
439
440     predicates.predicates.extend(substituted_predicates);
441     let predicates = predicates.instantiate_identity(fcx.tcx);
442     let predicates = fcx.normalize_associated_types_in(span, &predicates);
443
444     let obligations =
445         predicates.predicates
446                     .iter()
447                     .flat_map(|p| ty::wf::predicate_obligations(fcx,
448                                                                 fcx.param_env,
449                                                                 fcx.body_id,
450                                                                 p,
451                                                                 span));
452
453     for obligation in obligations {
454         fcx.register_predicate(obligation);
455     }
456 }
457
458 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
459                                     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
460                                     span: Span,
461                                     sig: ty::PolyFnSig<'tcx>,
462                                     def_id: DefId,
463                                     implied_bounds: &mut Vec<Ty<'tcx>>)
464 {
465     let sig = fcx.normalize_associated_types_in(span, &sig);
466     let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
467
468     for input_ty in sig.inputs() {
469         fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
470     }
471     implied_bounds.extend(sig.inputs());
472
473     fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
474
475     // FIXME(#25759) return types should not be implied bounds
476     implied_bounds.push(sig.output());
477
478     check_where_clauses(tcx, fcx, span, def_id);
479 }
480
481 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
482                                            method_sig: &hir::MethodSig,
483                                            method: &ty::AssociatedItem,
484                                            self_ty: Ty<'tcx>)
485 {
486     // check that the method has a valid receiver type, given the type `Self`
487     debug!("check_method_receiver({:?}, self_ty={:?})",
488             method, self_ty);
489
490     if !method.method_has_self_argument {
491         return;
492     }
493
494     let span = method_sig.decl.inputs[0].span;
495
496     let sig = fcx.tcx.fn_sig(method.def_id);
497     let sig = fcx.normalize_associated_types_in(span, &sig);
498     let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
499
500     debug!("check_method_receiver: sig={:?}", sig);
501
502     let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
503     let self_ty = fcx.tcx.liberate_late_bound_regions(
504         method.def_id,
505         &ty::Binder(self_ty)
506     );
507
508     let self_arg_ty = sig.inputs()[0];
509
510     let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
511     let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
512     let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
513         method.def_id,
514         &ty::Binder(self_arg_ty)
515     );
516
517     let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
518
519     loop {
520         if let Some((potential_self_ty, _)) = autoderef.next() {
521             debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
522                 potential_self_ty, self_ty);
523
524             if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
525                 autoderef.finalize();
526                 if let Some(mut err) = fcx.demand_eqtype_with_origin(
527                     &cause, self_ty, potential_self_ty) {
528                     err.emit();
529                 }
530                 break
531             }
532         } else {
533             fcx.tcx.sess.diagnostic().mut_span_err(
534                 span, &format!("invalid `self` type: {:?}", self_arg_ty))
535             .note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty))
536             .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
537             .code(DiagnosticId::Error("E0307".into()))
538             .emit();
539             return
540         }
541     }
542
543     let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
544     let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
545
546     if !fcx.tcx.features().arbitrary_self_types {
547         match self_kind {
548             ExplicitSelf::ByValue |
549             ExplicitSelf::ByReference(_, _) |
550             ExplicitSelf::ByBox => (),
551
552             ExplicitSelf::ByRawPointer(_) => {
553                 feature_gate::feature_err(
554                     &fcx.tcx.sess.parse_sess,
555                     "arbitrary_self_types",
556                     span,
557                     GateIssue::Language,
558                     "raw pointer `self` is unstable")
559                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
560                 .emit();
561             }
562
563             ExplicitSelf::Other => {
564                 feature_gate::feature_err(
565                     &fcx.tcx.sess.parse_sess,
566                     "arbitrary_self_types",
567                     span,
568                     GateIssue::Language,"arbitrary `self` types are unstable")
569                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
570                 .emit();
571             }
572         }
573     }
574 }
575
576 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
577                                     item: &hir::Item,
578                                     ast_generics: &hir::Generics)
579 {
580     let item_def_id = tcx.hir.local_def_id(item.id);
581     let ty = tcx.type_of(item_def_id);
582     if tcx.has_error_field(ty) {
583         return;
584     }
585
586     let ty_predicates = tcx.predicates_of(item_def_id);
587     assert_eq!(ty_predicates.parent, None);
588     let variances = tcx.variances_of(item_def_id);
589
590     let mut constrained_parameters: FxHashSet<_> =
591         variances.iter().enumerate()
592                     .filter(|&(_, &variance)| variance != ty::Bivariant)
593                     .map(|(index, _)| Parameter(index as u32))
594                     .collect();
595
596     identify_constrained_type_params(tcx,
597                                         ty_predicates.predicates.as_slice(),
598                                         None,
599                                         &mut constrained_parameters);
600
601     for (index, _) in variances.iter().enumerate() {
602         if constrained_parameters.contains(&Parameter(index as u32)) {
603             continue;
604         }
605
606         let (span, name) = match ast_generics.params[index] {
607             hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()),
608             hir::GenericParam::Type(ref tp) => (tp.span, tp.name),
609         };
610         report_bivariance(tcx, span, name);
611     }
612 }
613
614 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
615                         span: Span,
616                         param_name: ast::Name)
617 {
618     let mut err = error_392(tcx, span, param_name);
619
620     let suggested_marker_id = tcx.lang_items().phantom_data();
621     match suggested_marker_id {
622         Some(def_id) => {
623             err.help(
624                 &format!("consider removing `{}` or using a marker such as `{}`",
625                             param_name,
626                             tcx.item_path_str(def_id)));
627         }
628         None => {
629             // no lang items, no help!
630         }
631     }
632     err.emit();
633 }
634
635 fn reject_shadowing_type_parameters(tcx: TyCtxt, def_id: DefId) {
636     let generics = tcx.generics_of(def_id);
637     let parent = tcx.generics_of(generics.parent.unwrap());
638     let impl_params: FxHashMap<_, _> = parent.types
639                                        .iter()
640                                        .map(|tp| (tp.name, tp.def_id))
641                                        .collect();
642
643     for method_param in &generics.types {
644         if impl_params.contains_key(&method_param.name) {
645             // Tighten up the span to focus on only the shadowing type
646             let type_span = tcx.def_span(method_param.def_id);
647
648             // The expectation here is that the original trait declaration is
649             // local so it should be okay to just unwrap everything.
650             let trait_def_id = impl_params[&method_param.name];
651             let trait_decl_span = tcx.def_span(trait_def_id);
652             error_194(tcx, type_span, trait_decl_span, method_param.name);
653         }
654     }
655 }
656
657 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
658     tcx: TyCtxt<'a, 'tcx, 'tcx>,
659 }
660
661 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
662     pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
663                -> CheckTypeWellFormedVisitor<'a, 'gcx> {
664         CheckTypeWellFormedVisitor {
665             tcx,
666         }
667     }
668 }
669
670 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
671     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
672         NestedVisitorMap::None
673     }
674
675     fn visit_item(&mut self, i: &hir::Item) {
676         debug!("visit_item: {:?}", i);
677         let def_id = self.tcx.hir.local_def_id(i.id);
678         ty::maps::queries::check_item_well_formed::ensure(self.tcx, def_id);
679         intravisit::walk_item(self, i);
680     }
681
682     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
683         debug!("visit_trait_item: {:?}", trait_item);
684         let def_id = self.tcx.hir.local_def_id(trait_item.id);
685         ty::maps::queries::check_trait_item_well_formed::ensure(self.tcx, def_id);
686         intravisit::walk_trait_item(self, trait_item)
687     }
688
689     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
690         debug!("visit_impl_item: {:?}", impl_item);
691         let def_id = self.tcx.hir.local_def_id(impl_item.id);
692         ty::maps::queries::check_impl_item_well_formed::ensure(self.tcx, def_id);
693         intravisit::walk_impl_item(self, impl_item)
694     }
695 }
696
697 ///////////////////////////////////////////////////////////////////////////
698 // ADT
699
700 struct AdtVariant<'tcx> {
701     fields: Vec<AdtField<'tcx>>,
702 }
703
704 struct AdtField<'tcx> {
705     ty: Ty<'tcx>,
706     span: Span,
707 }
708
709 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
710     fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
711         let fields =
712             struct_def.fields().iter()
713             .map(|field| {
714                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
715                 let field_ty = self.normalize_associated_types_in(field.span,
716                                                                   &field_ty);
717                 AdtField { ty: field_ty, span: field.span }
718             })
719             .collect();
720         AdtVariant { fields: fields }
721     }
722
723     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
724         enum_def.variants.iter()
725             .map(|variant| self.non_enum_variant(&variant.node.data))
726             .collect()
727     }
728
729     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
730         match self.tcx.impl_trait_ref(impl_def_id) {
731             Some(ref trait_ref) => {
732                 // Trait impl: take implied bounds from all types that
733                 // appear in the trait reference.
734                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
735                 trait_ref.substs.types().collect()
736             }
737
738             None => {
739                 // Inherent impl: take implied bounds from the self type.
740                 let self_ty = self.tcx.type_of(impl_def_id);
741                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
742                 vec![self_ty]
743             }
744         }
745     }
746 }
747
748 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
749                        -> DiagnosticBuilder<'tcx> {
750     let mut err = struct_span_err!(tcx.sess, span, E0392,
751                   "parameter `{}` is never used", param_name);
752     err.span_label(span, "unused type parameter");
753     err
754 }
755
756 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: ast::Name) {
757     struct_span_err!(tcx.sess, span, E0194,
758               "type parameter `{}` shadows another type parameter of the same name",
759               name)
760         .span_label(span, "shadows another type parameter")
761         .span_label(trait_decl_span, format!("first `{}` declared here", name))
762         .emit();
763 }