]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
d2c96221991600637b337d26bfd21afd85cc1eda
[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, GenericParamDefKind, TypeFoldable};
17 use rustc::ty::subst::{Subst, Substs};
18 use rustc::ty::util::ExplicitSelf;
19 use rustc::util::nodemap::{FxHashSet, FxHashMap};
20 use rustc::middle::lang_items;
21 use rustc::infer::anon_types::may_define_existential_type;
22
23 use syntax::ast;
24 use syntax::feature_gate::{self, GateIssue};
25 use syntax_pos::Span;
26 use errors::{DiagnosticBuilder, DiagnosticId};
27
28 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
29 use rustc::hir;
30
31 /// Helper type of a temporary returned by .for_item(...).
32 /// Necessary because we can't write the following bound:
33 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>).
34 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
35     inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
36     id: ast::NodeId,
37     span: Span,
38     param_env: ty::ParamEnv<'tcx>,
39 }
40
41 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
42     fn with_fcx<F>(&'tcx mut self, f: F) where
43         F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
44                          TyCtxt<'b, 'gcx, 'gcx>) -> Vec<Ty<'tcx>>
45     {
46         let id = self.id;
47         let span = self.span;
48         let param_env = self.param_env;
49         self.inherited.enter(|inh| {
50             let fcx = FnCtxt::new(&inh, param_env, id);
51             if !inh.tcx.features().trivial_bounds {
52                 // As predicates are cached rather than obligations, this
53                 // needsto be called first so that they are checked with an
54                 // empty param_env.
55                 check_false_global_bounds(&fcx, span, id);
56             }
57             let wf_tys = f(&fcx, fcx.tcx.global_tcx());
58             fcx.select_all_obligations_or_error();
59             fcx.regionck_item(id, span, &wf_tys);
60         });
61     }
62 }
63
64 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
65 /// well-formed, meaning that they do not require any constraints not declared in the struct
66 /// definition itself. For example, this definition would be illegal:
67 ///
68 ///     struct Ref<'a, T> { x: &'a T }
69 ///
70 /// because the type did not declare that `T:'a`.
71 ///
72 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
73 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
74 /// the types first.
75 pub fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
76     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
77     let item = tcx.hir.expect_item(node_id);
78
79     debug!("check_item_well_formed(it.id={}, it.name={})",
80             item.id,
81             tcx.item_path_str(def_id));
82
83     match item.node {
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(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
102             let is_auto = tcx.impl_trait_ref(tcx.hir.local_def_id(item.id))
103                                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
104             if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
105                 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
106             }
107             if polarity == hir::ImplPolarity::Positive {
108                 check_impl(tcx, item, self_ty, trait_ref);
109             } else {
110                 // FIXME(#27579) what amount of WF checking do we need for neg impls?
111                 if trait_ref.is_some() && !is_auto {
112                     span_err!(tcx.sess, item.span, E0192,
113                                 "negative impls are only allowed for \
114                                 auto traits (e.g., `Send` and `Sync`)")
115                 }
116             }
117         }
118         hir::ItemKind::Fn(..) => {
119             check_item_fn(tcx, item);
120         }
121         hir::ItemKind::Static(..) => {
122             check_item_type(tcx, item);
123         }
124         hir::ItemKind::Const(..) => {
125             check_item_type(tcx, item);
126         }
127         hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
128             check_type_defn(tcx, item, false, |fcx| {
129                 vec![fcx.non_enum_variant(struct_def)]
130             });
131
132             check_variances_for_type_defn(tcx, item, ast_generics);
133         }
134         hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
135             check_type_defn(tcx, item, true, |fcx| {
136                 vec![fcx.non_enum_variant(struct_def)]
137             });
138
139             check_variances_for_type_defn(tcx, item, ast_generics);
140         }
141         hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
142             check_type_defn(tcx, item, true, |fcx| {
143                 fcx.enum_variants(enum_def)
144             });
145
146             check_variances_for_type_defn(tcx, item, ast_generics);
147         }
148         hir::ItemKind::Trait(..) => {
149             check_trait(tcx, item);
150         }
151         _ => {}
152     }
153 }
154
155 pub fn check_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
156     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
157     let trait_item = tcx.hir.expect_trait_item(node_id);
158
159     let method_sig = match trait_item.node {
160         hir::TraitItemKind::Method(ref sig, _) => Some(sig),
161         _ => None
162     };
163     check_associated_item(tcx, trait_item.id, trait_item.span, method_sig);
164 }
165
166 pub fn check_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
167     let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
168     let impl_item = tcx.hir.expect_impl_item(node_id);
169
170     let method_sig = match impl_item.node {
171         hir::ImplItemKind::Method(ref sig, _) => Some(sig),
172         _ => None
173     };
174     check_associated_item(tcx, impl_item.id, impl_item.span, method_sig);
175 }
176
177 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
178                             item_id: ast::NodeId,
179                             span: Span,
180                             sig_if_method: Option<&hir::MethodSig>) {
181     let code = ObligationCauseCode::MiscObligation;
182     for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
183         let item = fcx.tcx.associated_item(fcx.tcx.hir.local_def_id(item_id));
184
185         let (mut implied_bounds, self_ty) = match item.container {
186             ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
187             ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
188                                             fcx.tcx.type_of(def_id))
189         };
190
191         match item.kind {
192             ty::AssociatedKind::Const => {
193                 let ty = fcx.tcx.type_of(item.def_id);
194                 let ty = fcx.normalize_associated_types_in(span, &ty);
195                 fcx.register_wf_obligation(ty, span, code.clone());
196             }
197             ty::AssociatedKind::Method => {
198                 reject_shadowing_parameters(fcx.tcx, item.def_id);
199                 let sig = fcx.tcx.fn_sig(item.def_id);
200                 let sig = fcx.normalize_associated_types_in(span, &sig);
201                 check_fn_or_method(tcx, fcx, span, sig,
202                                         item.def_id, &mut implied_bounds);
203                 let sig_if_method = sig_if_method.expect("bad signature for method");
204                 check_method_receiver(fcx, sig_if_method, &item, self_ty);
205             }
206             ty::AssociatedKind::Type => {
207                 if item.defaultness.has_value() {
208                     let ty = fcx.tcx.type_of(item.def_id);
209                     let ty = fcx.normalize_associated_types_in(span, &ty);
210                     fcx.register_wf_obligation(ty, span, code.clone());
211                 }
212             }
213             ty::AssociatedKind::Existential => {
214                 // FIXME(oli-obk) implement existential types in trait impls
215                 unimplemented!()
216             }
217         }
218
219         implied_bounds
220     })
221 }
222
223 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
224                     -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
225     for_id(tcx, item.id, item.span)
226 }
227
228 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId, span: Span)
229                 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
230     let def_id = tcx.hir.local_def_id(id);
231     CheckWfFcxBuilder {
232         inherited: Inherited::build(tcx, def_id),
233         id,
234         span,
235         param_env: tcx.param_env(def_id),
236     }
237 }
238
239 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
240 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
241                                 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
242     where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
243 {
244     for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
245         let variants = lookup_fields(fcx);
246         let def_id = fcx.tcx.hir.local_def_id(item.id);
247         let packed = fcx.tcx.adt_def(def_id).repr.packed();
248
249         for variant in &variants {
250             // For DST, or when drop needs to copy things around, all
251             // intermediate types must be sized.
252             let needs_drop_copy = || {
253                 packed && {
254                     let ty = variant.fields.last().unwrap().ty;
255                     let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
256                         .unwrap_or_else(|| {
257                             span_bug!(item.span, "inference variables in {:?}", ty)
258                         });
259                     ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
260                 }
261             };
262             let unsized_len = if
263                 all_sized ||
264                 variant.fields.is_empty() ||
265                 needs_drop_copy()
266             {
267                 0
268             } else {
269                 1
270             };
271             for field in &variant.fields[..variant.fields.len() - unsized_len] {
272                 fcx.register_bound(
273                     field.ty,
274                     fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
275                     traits::ObligationCause::new(field.span,
276                                                     fcx.body_id,
277                                                     traits::FieldSized(match item.node.adt_kind() {
278                                                     Some(i) => i,
279                                                     None => bug!(),
280                                                     })));
281             }
282
283             // All field types must be well-formed.
284             for field in &variant.fields {
285                 fcx.register_wf_obligation(field.ty, field.span,
286                     ObligationCauseCode::MiscObligation)
287             }
288         }
289
290         check_where_clauses(tcx, fcx, item.span, def_id, None);
291
292         vec![] // no implied bounds in a struct def'n
293     });
294 }
295
296 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
297     let trait_def_id = tcx.hir.local_def_id(item.id);
298     for_item(tcx, item).with_fcx(|fcx, _| {
299         check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
300         vec![]
301     });
302 }
303
304 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
305     for_item(tcx, item).with_fcx(|fcx, tcx| {
306         let def_id = fcx.tcx.hir.local_def_id(item.id);
307         let sig = fcx.tcx.fn_sig(def_id);
308         let sig = fcx.normalize_associated_types_in(item.span, &sig);
309         let mut implied_bounds = vec![];
310         check_fn_or_method(tcx, fcx, item.span, sig,
311                                 def_id, &mut implied_bounds);
312         implied_bounds
313     })
314 }
315
316 fn check_item_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
317                     item: &hir::Item)
318 {
319     debug!("check_item_type: {:?}", item);
320
321     for_item(tcx, item).with_fcx(|fcx, _this| {
322         let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
323         let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
324
325         fcx.register_wf_obligation(item_ty, item.span, ObligationCauseCode::MiscObligation);
326
327         vec![] // no implied bounds in a const etc
328     });
329 }
330
331 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
332                 item: &hir::Item,
333                 ast_self_ty: &hir::Ty,
334                 ast_trait_ref: &Option<hir::TraitRef>)
335 {
336     debug!("check_impl: {:?}", item);
337
338     for_item(tcx, item).with_fcx(|fcx, tcx| {
339         let item_def_id = fcx.tcx.hir.local_def_id(item.id);
340
341         match *ast_trait_ref {
342             Some(ref ast_trait_ref) => {
343                 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
344                 let trait_ref =
345                     fcx.normalize_associated_types_in(
346                         ast_trait_ref.path.span, &trait_ref);
347                 let obligations =
348                     ty::wf::trait_obligations(fcx,
349                                                 fcx.param_env,
350                                                 fcx.body_id,
351                                                 &trait_ref,
352                                                 ast_trait_ref.path.span);
353                 for obligation in obligations {
354                     fcx.register_predicate(obligation);
355                 }
356             }
357             None => {
358                 let self_ty = fcx.tcx.type_of(item_def_id);
359                 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
360                 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
361                     ObligationCauseCode::MiscObligation);
362             }
363         }
364
365         check_where_clauses(tcx, fcx, item.span, item_def_id, None);
366
367         fcx.impl_implied_bounds(item_def_id, item.span)
368     });
369 }
370
371 /// Checks where clauses and inline bounds that are declared on def_id.
372 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
373     tcx: TyCtxt<'a, 'gcx, 'gcx>,
374     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
375     span: Span,
376     def_id: DefId,
377     return_ty: Option<Ty<'tcx>>,
378 ) {
379     use ty::subst::Subst;
380     use rustc::ty::TypeFoldable;
381
382     let predicates = fcx.tcx.predicates_of(def_id);
383
384     let generics = tcx.generics_of(def_id);
385     let is_our_default = |def: &ty::GenericParamDef| {
386         match def.kind {
387             GenericParamDefKind::Type { has_default, .. } => {
388                 has_default && def.index >= generics.parent_count as u32
389             }
390             _ => unreachable!()
391         }
392     };
393
394     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
395     // For example this forbids the declaration:
396     // struct Foo<T = Vec<[u32]>> { .. }
397     // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
398     for param in &generics.params {
399         if let GenericParamDefKind::Type {..} = param.kind {
400             if is_our_default(&param) {
401                 let ty = fcx.tcx.type_of(param.def_id);
402                 // ignore dependent defaults -- that is, where the default of one type
403                 // parameter includes another (e.g., <T, U = T>). In those cases, we can't
404                 // be sure if it will error or not as user might always specify the other.
405                 if !ty.needs_subst() {
406                     fcx.register_wf_obligation(ty, fcx.tcx.def_span(param.def_id),
407                         ObligationCauseCode::MiscObligation);
408                 }
409             }
410         }
411     }
412
413     // Check that trait predicates are WF when params are substituted by their defaults.
414     // We don't want to overly constrain the predicates that may be written but we want to
415     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
416     // Therefore we check if a predicate which contains a single type param
417     // with a concrete default is WF with that default substituted.
418     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
419     //
420     // First we build the defaulted substitution.
421     let substs = Substs::for_item(fcx.tcx, def_id, |param, _| {
422         match param.kind {
423             GenericParamDefKind::Lifetime => {
424                 // All regions are identity.
425                 fcx.tcx.mk_param_from_def(param)
426             }
427             GenericParamDefKind::Type {..} => {
428                 // If the param has a default,
429                 if is_our_default(param) {
430                     let default_ty = fcx.tcx.type_of(param.def_id);
431                     // and it's not a dependent default
432                     if !default_ty.needs_subst() {
433                         // then substitute with the default.
434                         return default_ty.into();
435                     }
436                 }
437                 // Mark unwanted params as err.
438                 fcx.tcx.types.err.into()
439             }
440         }
441     });
442     // Now we build the substituted predicates.
443     let default_obligations = predicates.predicates.iter().flat_map(|&pred| {
444         struct CountParams { params: FxHashSet<u32> }
445         impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
446             fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
447                 match t.sty {
448                     ty::TyParam(p) => {
449                         self.params.insert(p.idx);
450                         t.super_visit_with(self)
451                     }
452                     _ => t.super_visit_with(self)
453                 }
454             }
455
456             fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
457                 true
458             }
459         }
460         let mut param_count = CountParams { params: FxHashSet() };
461         let has_region = pred.visit_with(&mut param_count);
462         let substituted_pred = pred.subst(fcx.tcx, substs);
463         // Don't check non-defaulted params, dependent defaults (including lifetimes)
464         // or preds with multiple params.
465         if {
466             substituted_pred.references_error() || param_count.params.len() > 1
467                 || has_region
468         } {
469                 None
470         } else if predicates.predicates.contains(&substituted_pred) {
471             // Avoid duplication of predicates that contain no parameters, for example.
472             None
473         } else {
474             Some(substituted_pred)
475         }
476     }).map(|pred| {
477         // convert each of those into an obligation. So if you have
478         // something like `struct Foo<T: Copy = String>`, we would
479         // take that predicate `T: Copy`, substitute to `String: Copy`
480         // (actually that happens in the previous `flat_map` call),
481         // and then try to prove it (in this case, we'll fail).
482         //
483         // Note the subtle difference from how we handle `predicates`
484         // below: there, we are not trying to prove those predicates
485         // to be *true* but merely *well-formed*.
486         let pred = fcx.normalize_associated_types_in(span, &pred);
487         let cause = traits::ObligationCause::new(span, fcx.body_id, traits::ItemObligation(def_id));
488         traits::Obligation::new(cause, fcx.param_env, pred)
489     });
490
491     let mut predicates = predicates.instantiate_identity(fcx.tcx);
492
493     if let Some(return_ty) = return_ty {
494         predicates.predicates.extend(check_existential_types(tcx, fcx, def_id, span, return_ty));
495     }
496
497     let predicates = fcx.normalize_associated_types_in(span, &predicates);
498
499     debug!("check_where_clauses: predicates={:?}", predicates.predicates);
500     let wf_obligations =
501         predicates.predicates
502                     .iter()
503                     .flat_map(|p| ty::wf::predicate_obligations(fcx,
504                                                                 fcx.param_env,
505                                                                 fcx.body_id,
506                                                                 p,
507                                                                 span));
508
509     for obligation in wf_obligations.chain(default_obligations) {
510         debug!("next obligation cause: {:?}", obligation.cause);
511         fcx.register_predicate(obligation);
512     }
513 }
514
515 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
516                                     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
517                                     span: Span,
518                                     sig: ty::PolyFnSig<'tcx>,
519                                     def_id: DefId,
520                                     implied_bounds: &mut Vec<Ty<'tcx>>)
521 {
522     let sig = fcx.normalize_associated_types_in(span, &sig);
523     let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
524
525     for input_ty in sig.inputs() {
526         fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
527     }
528     implied_bounds.extend(sig.inputs());
529
530     fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
531
532     // FIXME(#25759) return types should not be implied bounds
533     implied_bounds.push(sig.output());
534
535     check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
536 }
537
538 fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>(
539     tcx: TyCtxt<'a, 'gcx, 'gcx>,
540     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
541     fn_def_id: DefId,
542     span: Span,
543     ty: Ty<'tcx>,
544 ) -> Vec<ty::Predicate<'tcx>> {
545     trace!("check_existential_types: {:?}, {:?}", ty, ty.sty);
546     let mut substituted_predicates = Vec::new();
547     ty.fold_with(&mut ty::fold::BottomUpFolder {
548         tcx: fcx.tcx,
549         fldop: |ty| {
550             if let ty::TyAnon(def_id, substs) = ty.sty {
551                 trace!("check_existential_types: anon_ty, {:?}, {:?}", def_id, substs);
552                 let generics = tcx.generics_of(def_id);
553                 // only check named existential types
554                 if generics.parent.is_none() {
555                     let anon_node_id = tcx.hir.as_local_node_id(def_id).unwrap();
556                     if may_define_existential_type(tcx, fn_def_id, anon_node_id) {
557                         trace!("check_existential_types may define. Generics: {:#?}", generics);
558                         for (subst, param) in substs.iter().zip(&generics.params) {
559                             if let ty::subst::UnpackedKind::Type(ty) = subst.unpack() {
560                                 match ty.sty {
561                                     ty::TyParam(..) => {},
562                                     // prevent `fn foo() -> Foo<u32>` from being defining
563                                     _ => {
564                                         tcx
565                                             .sess
566                                             .struct_span_err(
567                                                 span,
568                                                 "non-defining existential type use \
569                                                  in defining scope",
570                                             )
571                                             .span_note(
572                                                 tcx.def_span(param.def_id),
573                                                 &format!(
574                                                     "used non-generic type {} for \
575                                                      generic parameter",
576                                                     ty,
577                                                 ),
578                                             )
579                                             .emit();
580                                         return tcx.types.err;
581                                     },
582                                 } // match ty
583                             } // if let Type = subst
584                         } // for (subst, param)
585                     } // if may_define_existential_type
586
587                     // now register the bounds on the parameters of the existential type
588                     // so the parameters given by the function need to fulfil them
589                     // ```rust
590                     // existential type Foo<T: Bar>: 'static;
591                     // fn foo<U>() -> Foo<U> { .. *}
592                     // ```
593                     // becomes
594                     // ```rust
595                     // existential type Foo<T: Bar>: 'static;
596                     // fn foo<U: Bar>() -> Foo<U> { .. *}
597                     // ```
598                     let predicates = tcx.predicates_of(def_id);
599                     trace!(
600                         "check_existential_types may define. adding predicates: {:#?}",
601                         predicates,
602                     );
603                     for &pred in predicates.predicates.iter() {
604                         let substituted_pred = pred.subst(fcx.tcx, substs);
605                         // Avoid duplication of predicates that contain no parameters, for example.
606                         if !predicates.predicates.contains(&substituted_pred) {
607                             substituted_predicates.push(substituted_pred);
608                         }
609                     }
610                 } // if is_named_existential_type
611             } // if let TyAnon
612             ty
613         },
614     });
615     substituted_predicates
616 }
617
618 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
619                                            method_sig: &hir::MethodSig,
620                                            method: &ty::AssociatedItem,
621                                            self_ty: Ty<'tcx>)
622 {
623     // check that the method has a valid receiver type, given the type `Self`
624     debug!("check_method_receiver({:?}, self_ty={:?})",
625             method, self_ty);
626
627     if !method.method_has_self_argument {
628         return;
629     }
630
631     let span = method_sig.decl.inputs[0].span;
632
633     let sig = fcx.tcx.fn_sig(method.def_id);
634     let sig = fcx.normalize_associated_types_in(span, &sig);
635     let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
636
637     debug!("check_method_receiver: sig={:?}", sig);
638
639     let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
640     let self_ty = fcx.tcx.liberate_late_bound_regions(
641         method.def_id,
642         &ty::Binder::bind(self_ty)
643     );
644
645     let self_arg_ty = sig.inputs()[0];
646
647     let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
648     let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
649     let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
650         method.def_id,
651         &ty::Binder::bind(self_arg_ty)
652     );
653
654     let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
655
656     loop {
657         if let Some((potential_self_ty, _)) = autoderef.next() {
658             debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
659                 potential_self_ty, self_ty);
660
661             if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
662                 autoderef.finalize();
663                 if let Some(mut err) = fcx.demand_eqtype_with_origin(
664                     &cause, self_ty, potential_self_ty) {
665                     err.emit();
666                 }
667                 break
668             }
669         } else {
670             fcx.tcx.sess.diagnostic().mut_span_err(
671                 span, &format!("invalid `self` type: {:?}", self_arg_ty))
672             .note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty))
673             .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
674             .code(DiagnosticId::Error("E0307".into()))
675             .emit();
676             return
677         }
678     }
679
680     let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
681     let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
682
683     if !fcx.tcx.features().arbitrary_self_types {
684         match self_kind {
685             ExplicitSelf::ByValue |
686             ExplicitSelf::ByReference(_, _) |
687             ExplicitSelf::ByBox => (),
688
689             ExplicitSelf::ByRawPointer(_) => {
690                 feature_gate::feature_err(
691                     &fcx.tcx.sess.parse_sess,
692                     "arbitrary_self_types",
693                     span,
694                     GateIssue::Language,
695                     "raw pointer `self` is unstable")
696                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
697                 .emit();
698             }
699
700             ExplicitSelf::Other => {
701                 feature_gate::feature_err(
702                     &fcx.tcx.sess.parse_sess,
703                     "arbitrary_self_types",
704                     span,
705                     GateIssue::Language,"arbitrary `self` types are unstable")
706                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
707                 .emit();
708             }
709         }
710     }
711 }
712
713 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
714                                            item: &hir::Item,
715                                            hir_generics: &hir::Generics)
716 {
717     let item_def_id = tcx.hir.local_def_id(item.id);
718     let ty = tcx.type_of(item_def_id);
719     if tcx.has_error_field(ty) {
720         return;
721     }
722
723     let ty_predicates = tcx.predicates_of(item_def_id);
724     assert_eq!(ty_predicates.parent, None);
725     let variances = tcx.variances_of(item_def_id);
726
727     let mut constrained_parameters: FxHashSet<_> =
728         variances.iter().enumerate()
729                     .filter(|&(_, &variance)| variance != ty::Bivariant)
730                     .map(|(index, _)| Parameter(index as u32))
731                     .collect();
732
733     identify_constrained_type_params(tcx,
734                                         ty_predicates.predicates.as_slice(),
735                                         None,
736                                         &mut constrained_parameters);
737
738     for (index, _) in variances.iter().enumerate() {
739         if constrained_parameters.contains(&Parameter(index as u32)) {
740             continue;
741         }
742
743         let param = &hir_generics.params[index];
744         report_bivariance(tcx, param.span, param.name.ident().name);
745     }
746 }
747
748 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
749                         span: Span,
750                         param_name: ast::Name)
751 {
752     let mut err = error_392(tcx, span, param_name);
753
754     let suggested_marker_id = tcx.lang_items().phantom_data();
755     match suggested_marker_id {
756         Some(def_id) => {
757             err.help(
758                 &format!("consider removing `{}` or using a marker such as `{}`",
759                             param_name,
760                             tcx.item_path_str(def_id)));
761         }
762         None => {
763             // no lang items, no help!
764         }
765     }
766     err.emit();
767 }
768
769 fn reject_shadowing_parameters(tcx: TyCtxt, def_id: DefId) {
770     let generics = tcx.generics_of(def_id);
771     let parent = tcx.generics_of(generics.parent.unwrap());
772     let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
773         GenericParamDefKind::Lifetime => None,
774         GenericParamDefKind::Type {..} => Some((param.name, param.def_id)),
775     }).collect();
776
777     for method_param in &generics.params {
778         match method_param.kind {
779             // Shadowing is checked in resolve_lifetime.
780             GenericParamDefKind::Lifetime => continue,
781             _ => {},
782         };
783         if impl_params.contains_key(&method_param.name) {
784             // Tighten up the span to focus on only the shadowing type
785             let type_span = tcx.def_span(method_param.def_id);
786
787             // The expectation here is that the original trait declaration is
788             // local so it should be okay to just unwrap everything.
789             let trait_def_id = impl_params[&method_param.name];
790             let trait_decl_span = tcx.def_span(trait_def_id);
791             error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
792         }
793     }
794 }
795
796 /// Feature gates RFC 2056 - trivial bounds, checking for global bounds that
797 /// aren't true.
798 fn check_false_global_bounds<'a, 'gcx, 'tcx>(
799         fcx: &FnCtxt<'a, 'gcx, 'tcx>,
800         span: Span,
801         id: ast::NodeId,
802 ) {
803     use rustc::ty::TypeFoldable;
804
805     let empty_env = ty::ParamEnv::empty();
806
807     let def_id = fcx.tcx.hir.local_def_id(id);
808     let predicates = fcx.tcx.predicates_of(def_id).predicates;
809     // Check elaborated bounds
810     let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
811
812     for pred in implied_obligations {
813         // Match the existing behavior.
814         if pred.is_global() && !pred.has_late_bound_regions() {
815             let pred = fcx.normalize_associated_types_in(span, &pred);
816             let obligation = traits::Obligation::new(
817                 traits::ObligationCause::new(
818                     span,
819                     id,
820                     traits::TrivialBound,
821                 ),
822                 empty_env,
823                 pred,
824             );
825             fcx.register_predicate(obligation);
826         }
827     }
828
829     fcx.select_all_obligations_or_error();
830 }
831
832 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
833     tcx: TyCtxt<'a, 'tcx, 'tcx>,
834 }
835
836 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
837     pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
838                -> CheckTypeWellFormedVisitor<'a, 'gcx> {
839         CheckTypeWellFormedVisitor {
840             tcx,
841         }
842     }
843 }
844
845 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
846     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
847         NestedVisitorMap::None
848     }
849
850     fn visit_item(&mut self, i: &hir::Item) {
851         debug!("visit_item: {:?}", i);
852         let def_id = self.tcx.hir.local_def_id(i.id);
853         ty::query::queries::check_item_well_formed::ensure(self.tcx, def_id);
854         intravisit::walk_item(self, i);
855     }
856
857     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
858         debug!("visit_trait_item: {:?}", trait_item);
859         let def_id = self.tcx.hir.local_def_id(trait_item.id);
860         ty::query::queries::check_trait_item_well_formed::ensure(self.tcx, def_id);
861         intravisit::walk_trait_item(self, trait_item)
862     }
863
864     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
865         debug!("visit_impl_item: {:?}", impl_item);
866         let def_id = self.tcx.hir.local_def_id(impl_item.id);
867         ty::query::queries::check_impl_item_well_formed::ensure(self.tcx, def_id);
868         intravisit::walk_impl_item(self, impl_item)
869     }
870 }
871
872 ///////////////////////////////////////////////////////////////////////////
873 // ADT
874
875 struct AdtVariant<'tcx> {
876     fields: Vec<AdtField<'tcx>>,
877 }
878
879 struct AdtField<'tcx> {
880     ty: Ty<'tcx>,
881     span: Span,
882 }
883
884 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
885     fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
886         let fields =
887             struct_def.fields().iter()
888             .map(|field| {
889                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
890                 let field_ty = self.normalize_associated_types_in(field.span,
891                                                                   &field_ty);
892                 AdtField { ty: field_ty, span: field.span }
893             })
894             .collect();
895         AdtVariant { fields: fields }
896     }
897
898     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
899         enum_def.variants.iter()
900             .map(|variant| self.non_enum_variant(&variant.node.data))
901             .collect()
902     }
903
904     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
905         match self.tcx.impl_trait_ref(impl_def_id) {
906             Some(ref trait_ref) => {
907                 // Trait impl: take implied bounds from all types that
908                 // appear in the trait reference.
909                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
910                 trait_ref.substs.types().collect()
911             }
912
913             None => {
914                 // Inherent impl: take implied bounds from the self type.
915                 let self_ty = self.tcx.type_of(impl_def_id);
916                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
917                 vec![self_ty]
918             }
919         }
920     }
921 }
922
923 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
924                        -> DiagnosticBuilder<'tcx> {
925     let mut err = struct_span_err!(tcx.sess, span, E0392,
926                   "parameter `{}` is never used", param_name);
927     err.span_label(span, "unused type parameter");
928     err
929 }
930
931 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: &str) {
932     struct_span_err!(tcx.sess, span, E0194,
933               "type parameter `{}` shadows another type parameter of the same name",
934               name)
935         .span_label(span, "shadows another type parameter")
936         .span_label(trait_decl_span, format!("first `{}` declared here", name))
937         .emit();
938 }