]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
Implement associated existential types
[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                 // do nothing, existential types check themselves
215             }
216         }
217
218         implied_bounds
219     })
220 }
221
222 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
223                     -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
224     for_id(tcx, item.id, item.span)
225 }
226
227 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId, span: Span)
228                 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
229     let def_id = tcx.hir.local_def_id(id);
230     CheckWfFcxBuilder {
231         inherited: Inherited::build(tcx, def_id),
232         id,
233         span,
234         param_env: tcx.param_env(def_id),
235     }
236 }
237
238 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
239 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
240                                 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
241     where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
242 {
243     for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
244         let variants = lookup_fields(fcx);
245         let def_id = fcx.tcx.hir.local_def_id(item.id);
246         let packed = fcx.tcx.adt_def(def_id).repr.packed();
247
248         for variant in &variants {
249             // For DST, or when drop needs to copy things around, all
250             // intermediate types must be sized.
251             let needs_drop_copy = || {
252                 packed && {
253                     let ty = variant.fields.last().unwrap().ty;
254                     let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
255                         .unwrap_or_else(|| {
256                             span_bug!(item.span, "inference variables in {:?}", ty)
257                         });
258                     ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
259                 }
260             };
261             let unsized_len = if
262                 all_sized ||
263                 variant.fields.is_empty() ||
264                 needs_drop_copy()
265             {
266                 0
267             } else {
268                 1
269             };
270             for field in &variant.fields[..variant.fields.len() - unsized_len] {
271                 fcx.register_bound(
272                     field.ty,
273                     fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
274                     traits::ObligationCause::new(field.span,
275                                                     fcx.body_id,
276                                                     traits::FieldSized(match item.node.adt_kind() {
277                                                     Some(i) => i,
278                                                     None => bug!(),
279                                                     })));
280             }
281
282             // All field types must be well-formed.
283             for field in &variant.fields {
284                 fcx.register_wf_obligation(field.ty, field.span,
285                     ObligationCauseCode::MiscObligation)
286             }
287         }
288
289         check_where_clauses(tcx, fcx, item.span, def_id, None);
290
291         vec![] // no implied bounds in a struct def'n
292     });
293 }
294
295 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
296     let trait_def_id = tcx.hir.local_def_id(item.id);
297     for_item(tcx, item).with_fcx(|fcx, _| {
298         check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
299         vec![]
300     });
301 }
302
303 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
304     for_item(tcx, item).with_fcx(|fcx, tcx| {
305         let def_id = fcx.tcx.hir.local_def_id(item.id);
306         let sig = fcx.tcx.fn_sig(def_id);
307         let sig = fcx.normalize_associated_types_in(item.span, &sig);
308         let mut implied_bounds = vec![];
309         check_fn_or_method(tcx, fcx, item.span, sig,
310                                 def_id, &mut implied_bounds);
311         implied_bounds
312     })
313 }
314
315 fn check_item_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
316                     item: &hir::Item)
317 {
318     debug!("check_item_type: {:?}", item);
319
320     for_item(tcx, item).with_fcx(|fcx, _this| {
321         let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
322         let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
323
324         fcx.register_wf_obligation(item_ty, item.span, ObligationCauseCode::MiscObligation);
325
326         vec![] // no implied bounds in a const etc
327     });
328 }
329
330 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
331                 item: &hir::Item,
332                 ast_self_ty: &hir::Ty,
333                 ast_trait_ref: &Option<hir::TraitRef>)
334 {
335     debug!("check_impl: {:?}", item);
336
337     for_item(tcx, item).with_fcx(|fcx, tcx| {
338         let item_def_id = fcx.tcx.hir.local_def_id(item.id);
339
340         match *ast_trait_ref {
341             Some(ref ast_trait_ref) => {
342                 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
343                 let trait_ref =
344                     fcx.normalize_associated_types_in(
345                         ast_trait_ref.path.span, &trait_ref);
346                 let obligations =
347                     ty::wf::trait_obligations(fcx,
348                                                 fcx.param_env,
349                                                 fcx.body_id,
350                                                 &trait_ref,
351                                                 ast_trait_ref.path.span);
352                 for obligation in obligations {
353                     fcx.register_predicate(obligation);
354                 }
355             }
356             None => {
357                 let self_ty = fcx.tcx.type_of(item_def_id);
358                 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
359                 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
360                     ObligationCauseCode::MiscObligation);
361             }
362         }
363
364         check_where_clauses(tcx, fcx, item.span, item_def_id, None);
365
366         fcx.impl_implied_bounds(item_def_id, item.span)
367     });
368 }
369
370 /// Checks where clauses and inline bounds that are declared on def_id.
371 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
372     tcx: TyCtxt<'a, 'gcx, 'gcx>,
373     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
374     span: Span,
375     def_id: DefId,
376     return_ty: Option<Ty<'tcx>>,
377 ) {
378     use ty::subst::Subst;
379     use rustc::ty::TypeFoldable;
380
381     let predicates = fcx.tcx.predicates_of(def_id);
382
383     let generics = tcx.generics_of(def_id);
384     let is_our_default = |def: &ty::GenericParamDef| {
385         match def.kind {
386             GenericParamDefKind::Type { has_default, .. } => {
387                 has_default && def.index >= generics.parent_count as u32
388             }
389             _ => unreachable!()
390         }
391     };
392
393     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
394     // For example this forbids the declaration:
395     // struct Foo<T = Vec<[u32]>> { .. }
396     // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
397     for param in &generics.params {
398         if let GenericParamDefKind::Type {..} = param.kind {
399             if is_our_default(&param) {
400                 let ty = fcx.tcx.type_of(param.def_id);
401                 // ignore dependent defaults -- that is, where the default of one type
402                 // parameter includes another (e.g., <T, U = T>). In those cases, we can't
403                 // be sure if it will error or not as user might always specify the other.
404                 if !ty.needs_subst() {
405                     fcx.register_wf_obligation(ty, fcx.tcx.def_span(param.def_id),
406                         ObligationCauseCode::MiscObligation);
407                 }
408             }
409         }
410     }
411
412     // Check that trait predicates are WF when params are substituted by their defaults.
413     // We don't want to overly constrain the predicates that may be written but we want to
414     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
415     // Therefore we check if a predicate which contains a single type param
416     // with a concrete default is WF with that default substituted.
417     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
418     //
419     // First we build the defaulted substitution.
420     let substs = Substs::for_item(fcx.tcx, def_id, |param, _| {
421         match param.kind {
422             GenericParamDefKind::Lifetime => {
423                 // All regions are identity.
424                 fcx.tcx.mk_param_from_def(param)
425             }
426             GenericParamDefKind::Type {..} => {
427                 // If the param has a default,
428                 if is_our_default(param) {
429                     let default_ty = fcx.tcx.type_of(param.def_id);
430                     // and it's not a dependent default
431                     if !default_ty.needs_subst() {
432                         // then substitute with the default.
433                         return default_ty.into();
434                     }
435                 }
436                 // Mark unwanted params as err.
437                 fcx.tcx.types.err.into()
438             }
439         }
440     });
441     // Now we build the substituted predicates.
442     let default_obligations = predicates.predicates.iter().flat_map(|&pred| {
443         struct CountParams { params: FxHashSet<u32> }
444         impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
445             fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
446                 match t.sty {
447                     ty::TyParam(p) => {
448                         self.params.insert(p.idx);
449                         t.super_visit_with(self)
450                     }
451                     _ => t.super_visit_with(self)
452                 }
453             }
454
455             fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
456                 true
457             }
458         }
459         let mut param_count = CountParams { params: FxHashSet() };
460         let has_region = pred.visit_with(&mut param_count);
461         let substituted_pred = pred.subst(fcx.tcx, substs);
462         // Don't check non-defaulted params, dependent defaults (including lifetimes)
463         // or preds with multiple params.
464         if {
465             substituted_pred.references_error() || param_count.params.len() > 1
466                 || has_region
467         } {
468                 None
469         } else if predicates.predicates.contains(&substituted_pred) {
470             // Avoid duplication of predicates that contain no parameters, for example.
471             None
472         } else {
473             Some(substituted_pred)
474         }
475     }).map(|pred| {
476         // convert each of those into an obligation. So if you have
477         // something like `struct Foo<T: Copy = String>`, we would
478         // take that predicate `T: Copy`, substitute to `String: Copy`
479         // (actually that happens in the previous `flat_map` call),
480         // and then try to prove it (in this case, we'll fail).
481         //
482         // Note the subtle difference from how we handle `predicates`
483         // below: there, we are not trying to prove those predicates
484         // to be *true* but merely *well-formed*.
485         let pred = fcx.normalize_associated_types_in(span, &pred);
486         let cause = traits::ObligationCause::new(span, fcx.body_id, traits::ItemObligation(def_id));
487         traits::Obligation::new(cause, fcx.param_env, pred)
488     });
489
490     let mut predicates = predicates.instantiate_identity(fcx.tcx);
491
492     if let Some(return_ty) = return_ty {
493         predicates.predicates.extend(check_existential_types(tcx, fcx, def_id, span, return_ty));
494     }
495
496     let predicates = fcx.normalize_associated_types_in(span, &predicates);
497
498     debug!("check_where_clauses: predicates={:?}", predicates.predicates);
499     let wf_obligations =
500         predicates.predicates
501                     .iter()
502                     .flat_map(|p| ty::wf::predicate_obligations(fcx,
503                                                                 fcx.param_env,
504                                                                 fcx.body_id,
505                                                                 p,
506                                                                 span));
507
508     for obligation in wf_obligations.chain(default_obligations) {
509         debug!("next obligation cause: {:?}", obligation.cause);
510         fcx.register_predicate(obligation);
511     }
512 }
513
514 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
515                                     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
516                                     span: Span,
517                                     sig: ty::PolyFnSig<'tcx>,
518                                     def_id: DefId,
519                                     implied_bounds: &mut Vec<Ty<'tcx>>)
520 {
521     let sig = fcx.normalize_associated_types_in(span, &sig);
522     let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
523
524     for input_ty in sig.inputs() {
525         fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
526     }
527     implied_bounds.extend(sig.inputs());
528
529     fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
530
531     // FIXME(#25759) return types should not be implied bounds
532     implied_bounds.push(sig.output());
533
534     check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
535 }
536
537 /// Checks "defining uses" of existential types to ensure that they meet the restrictions laid for
538 /// "higher-order pattern unification".
539 /// This ensures that inference is tractable.
540 /// In particular, definitions of existential types can only use other generics as arguments,
541 /// and they cannot repeat an argument. Example:
542 ///
543 /// ```rust
544 /// existential type Foo<A, B>;
545 ///
546 /// // ok -- `Foo` is applied to two distinct, generic types.
547 /// fn a<T, U>() -> Foo<T, U> { .. }
548 ///
549 /// // not ok -- `Foo` is applied to `T` twice.
550 /// fn b<T>() -> Foo<T, T> { .. }
551 ///
552 ///
553 /// // not ok -- `Foo` is applied to a non-generic type.
554 /// fn b<T>() -> Foo<T, u32> { .. }
555 /// ```
556 ///
557 fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>(
558     tcx: TyCtxt<'a, 'gcx, 'gcx>,
559     fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
560     fn_def_id: DefId,
561     span: Span,
562     ty: Ty<'tcx>,
563 ) -> Vec<ty::Predicate<'tcx>> {
564     trace!("check_existential_types: {:?}, {:?}", ty, ty.sty);
565     let mut substituted_predicates = Vec::new();
566     ty.fold_with(&mut ty::fold::BottomUpFolder {
567         tcx: fcx.tcx,
568         fldop: |ty| {
569             if let ty::TyAnon(def_id, substs) = ty.sty {
570                 trace!("check_existential_types: anon_ty, {:?}, {:?}", def_id, substs);
571                 let generics = tcx.generics_of(def_id);
572                 // only check named existential types
573                 if generics.parent.is_none() {
574                     let anon_node_id = tcx.hir.as_local_node_id(def_id).unwrap();
575                     if may_define_existential_type(tcx, fn_def_id, anon_node_id) {
576                         trace!("check_existential_types may define. Generics: {:#?}", generics);
577                         let mut seen: FxHashMap<_, Vec<_>> = FxHashMap();
578                         for (subst, param) in substs.iter().zip(&generics.params) {
579                             match subst.unpack() {
580                                 ty::subst::UnpackedKind::Type(ty) => match ty.sty {
581                                     ty::TyParam(..) => {},
582                                     // prevent `fn foo() -> Foo<u32>` from being defining
583                                     _ => {
584                                         tcx
585                                             .sess
586                                             .struct_span_err(
587                                                 span,
588                                                 "non-defining existential type use \
589                                                  in defining scope",
590                                             )
591                                             .span_note(
592                                                 tcx.def_span(param.def_id),
593                                                 &format!(
594                                                     "used non-generic type {} for \
595                                                      generic parameter",
596                                                     ty,
597                                                 ),
598                                             )
599                                             .emit();
600                                     },
601                                 }, // match ty
602                                 ty::subst::UnpackedKind::Lifetime(region) => {
603                                     let param_span = tcx.def_span(param.def_id);
604                                     if let ty::ReStatic = region {
605                                         tcx
606                                             .sess
607                                             .struct_span_err(
608                                                 span,
609                                                 "non-defining existential type use \
610                                                     in defining scope",
611                                             )
612                                             .span_label(
613                                                 param_span,
614                                                 "cannot use static lifetime, use a bound lifetime \
615                                                 instead or remove the lifetime parameter from the \
616                                                 existential type",
617                                             )
618                                             .emit();
619                                     } else {
620                                         seen.entry(region).or_default().push(param_span);
621                                     }
622                                 },
623                             } // match subst
624                         } // for (subst, param)
625                         for (_, spans) in seen {
626                             if spans.len() > 1 {
627                                 tcx
628                                     .sess
629                                     .struct_span_err(
630                                         span,
631                                         "non-defining existential type use \
632                                             in defining scope",
633                                     ).
634                                     span_note(
635                                         spans,
636                                         "lifetime used multiple times",
637                                     )
638                                     .emit();
639                             }
640                         }
641                     } // if may_define_existential_type
642
643                     // now register the bounds on the parameters of the existential type
644                     // so the parameters given by the function need to fulfil them
645                     // ```rust
646                     // existential type Foo<T: Bar>: 'static;
647                     // fn foo<U>() -> Foo<U> { .. *}
648                     // ```
649                     // becomes
650                     // ```rust
651                     // existential type Foo<T: Bar>: 'static;
652                     // fn foo<U: Bar>() -> Foo<U> { .. *}
653                     // ```
654                     let predicates = tcx.predicates_of(def_id);
655                     trace!(
656                         "check_existential_types may define. adding predicates: {:#?}",
657                         predicates,
658                     );
659                     for &pred in predicates.predicates.iter() {
660                         let substituted_pred = pred.subst(fcx.tcx, substs);
661                         // Avoid duplication of predicates that contain no parameters, for example.
662                         if !predicates.predicates.contains(&substituted_pred) {
663                             substituted_predicates.push(substituted_pred);
664                         }
665                     }
666                 } // if is_named_existential_type
667             } // if let TyAnon
668             ty
669         },
670         reg_op: |reg| reg,
671     });
672     substituted_predicates
673 }
674
675 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
676                                            method_sig: &hir::MethodSig,
677                                            method: &ty::AssociatedItem,
678                                            self_ty: Ty<'tcx>)
679 {
680     // check that the method has a valid receiver type, given the type `Self`
681     debug!("check_method_receiver({:?}, self_ty={:?})",
682             method, self_ty);
683
684     if !method.method_has_self_argument {
685         return;
686     }
687
688     let span = method_sig.decl.inputs[0].span;
689
690     let sig = fcx.tcx.fn_sig(method.def_id);
691     let sig = fcx.normalize_associated_types_in(span, &sig);
692     let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
693
694     debug!("check_method_receiver: sig={:?}", sig);
695
696     let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
697     let self_ty = fcx.tcx.liberate_late_bound_regions(
698         method.def_id,
699         &ty::Binder::bind(self_ty)
700     );
701
702     let self_arg_ty = sig.inputs()[0];
703
704     let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
705     let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
706     let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
707         method.def_id,
708         &ty::Binder::bind(self_arg_ty)
709     );
710
711     let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
712
713     loop {
714         if let Some((potential_self_ty, _)) = autoderef.next() {
715             debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
716                 potential_self_ty, self_ty);
717
718             if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
719                 autoderef.finalize();
720                 if let Some(mut err) = fcx.demand_eqtype_with_origin(
721                     &cause, self_ty, potential_self_ty) {
722                     err.emit();
723                 }
724                 break
725             }
726         } else {
727             fcx.tcx.sess.diagnostic().mut_span_err(
728                 span, &format!("invalid `self` type: {:?}", self_arg_ty))
729             .note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty))
730             .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
731             .code(DiagnosticId::Error("E0307".into()))
732             .emit();
733             return
734         }
735     }
736
737     let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
738     let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
739
740     if !fcx.tcx.features().arbitrary_self_types {
741         match self_kind {
742             ExplicitSelf::ByValue |
743             ExplicitSelf::ByReference(_, _) |
744             ExplicitSelf::ByBox => (),
745
746             ExplicitSelf::ByRawPointer(_) => {
747                 feature_gate::feature_err(
748                     &fcx.tcx.sess.parse_sess,
749                     "arbitrary_self_types",
750                     span,
751                     GateIssue::Language,
752                     "raw pointer `self` is unstable")
753                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
754                 .emit();
755             }
756
757             ExplicitSelf::Other => {
758                 feature_gate::feature_err(
759                     &fcx.tcx.sess.parse_sess,
760                     "arbitrary_self_types",
761                     span,
762                     GateIssue::Language,"arbitrary `self` types are unstable")
763                 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
764                 .emit();
765             }
766         }
767     }
768 }
769
770 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
771                                            item: &hir::Item,
772                                            hir_generics: &hir::Generics)
773 {
774     let item_def_id = tcx.hir.local_def_id(item.id);
775     let ty = tcx.type_of(item_def_id);
776     if tcx.has_error_field(ty) {
777         return;
778     }
779
780     let ty_predicates = tcx.predicates_of(item_def_id);
781     assert_eq!(ty_predicates.parent, None);
782     let variances = tcx.variances_of(item_def_id);
783
784     let mut constrained_parameters: FxHashSet<_> =
785         variances.iter().enumerate()
786                     .filter(|&(_, &variance)| variance != ty::Bivariant)
787                     .map(|(index, _)| Parameter(index as u32))
788                     .collect();
789
790     identify_constrained_type_params(tcx,
791                                         ty_predicates.predicates.as_slice(),
792                                         None,
793                                         &mut constrained_parameters);
794
795     for (index, _) in variances.iter().enumerate() {
796         if constrained_parameters.contains(&Parameter(index as u32)) {
797             continue;
798         }
799
800         let param = &hir_generics.params[index];
801         report_bivariance(tcx, param.span, param.name.ident().name);
802     }
803 }
804
805 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
806                         span: Span,
807                         param_name: ast::Name)
808 {
809     let mut err = error_392(tcx, span, param_name);
810
811     let suggested_marker_id = tcx.lang_items().phantom_data();
812     match suggested_marker_id {
813         Some(def_id) => {
814             err.help(
815                 &format!("consider removing `{}` or using a marker such as `{}`",
816                             param_name,
817                             tcx.item_path_str(def_id)));
818         }
819         None => {
820             // no lang items, no help!
821         }
822     }
823     err.emit();
824 }
825
826 fn reject_shadowing_parameters(tcx: TyCtxt, def_id: DefId) {
827     let generics = tcx.generics_of(def_id);
828     let parent = tcx.generics_of(generics.parent.unwrap());
829     let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
830         GenericParamDefKind::Lifetime => None,
831         GenericParamDefKind::Type {..} => Some((param.name, param.def_id)),
832     }).collect();
833
834     for method_param in &generics.params {
835         match method_param.kind {
836             // Shadowing is checked in resolve_lifetime.
837             GenericParamDefKind::Lifetime => continue,
838             _ => {},
839         };
840         if impl_params.contains_key(&method_param.name) {
841             // Tighten up the span to focus on only the shadowing type
842             let type_span = tcx.def_span(method_param.def_id);
843
844             // The expectation here is that the original trait declaration is
845             // local so it should be okay to just unwrap everything.
846             let trait_def_id = impl_params[&method_param.name];
847             let trait_decl_span = tcx.def_span(trait_def_id);
848             error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
849         }
850     }
851 }
852
853 /// Feature gates RFC 2056 - trivial bounds, checking for global bounds that
854 /// aren't true.
855 fn check_false_global_bounds<'a, 'gcx, 'tcx>(
856         fcx: &FnCtxt<'a, 'gcx, 'tcx>,
857         span: Span,
858         id: ast::NodeId,
859 ) {
860     use rustc::ty::TypeFoldable;
861
862     let empty_env = ty::ParamEnv::empty();
863
864     let def_id = fcx.tcx.hir.local_def_id(id);
865     let predicates = fcx.tcx.predicates_of(def_id).predicates;
866     // Check elaborated bounds
867     let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
868
869     for pred in implied_obligations {
870         // Match the existing behavior.
871         if pred.is_global() && !pred.has_late_bound_regions() {
872             let pred = fcx.normalize_associated_types_in(span, &pred);
873             let obligation = traits::Obligation::new(
874                 traits::ObligationCause::new(
875                     span,
876                     id,
877                     traits::TrivialBound,
878                 ),
879                 empty_env,
880                 pred,
881             );
882             fcx.register_predicate(obligation);
883         }
884     }
885
886     fcx.select_all_obligations_or_error();
887 }
888
889 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
890     tcx: TyCtxt<'a, 'tcx, 'tcx>,
891 }
892
893 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
894     pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
895                -> CheckTypeWellFormedVisitor<'a, 'gcx> {
896         CheckTypeWellFormedVisitor {
897             tcx,
898         }
899     }
900 }
901
902 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
903     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
904         NestedVisitorMap::None
905     }
906
907     fn visit_item(&mut self, i: &hir::Item) {
908         debug!("visit_item: {:?}", i);
909         let def_id = self.tcx.hir.local_def_id(i.id);
910         ty::query::queries::check_item_well_formed::ensure(self.tcx, def_id);
911         intravisit::walk_item(self, i);
912     }
913
914     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
915         debug!("visit_trait_item: {:?}", trait_item);
916         let def_id = self.tcx.hir.local_def_id(trait_item.id);
917         ty::query::queries::check_trait_item_well_formed::ensure(self.tcx, def_id);
918         intravisit::walk_trait_item(self, trait_item)
919     }
920
921     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
922         debug!("visit_impl_item: {:?}", impl_item);
923         let def_id = self.tcx.hir.local_def_id(impl_item.id);
924         ty::query::queries::check_impl_item_well_formed::ensure(self.tcx, def_id);
925         intravisit::walk_impl_item(self, impl_item)
926     }
927 }
928
929 ///////////////////////////////////////////////////////////////////////////
930 // ADT
931
932 struct AdtVariant<'tcx> {
933     fields: Vec<AdtField<'tcx>>,
934 }
935
936 struct AdtField<'tcx> {
937     ty: Ty<'tcx>,
938     span: Span,
939 }
940
941 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
942     fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
943         let fields =
944             struct_def.fields().iter()
945             .map(|field| {
946                 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
947                 let field_ty = self.normalize_associated_types_in(field.span,
948                                                                   &field_ty);
949                 AdtField { ty: field_ty, span: field.span }
950             })
951             .collect();
952         AdtVariant { fields: fields }
953     }
954
955     fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
956         enum_def.variants.iter()
957             .map(|variant| self.non_enum_variant(&variant.node.data))
958             .collect()
959     }
960
961     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
962         match self.tcx.impl_trait_ref(impl_def_id) {
963             Some(ref trait_ref) => {
964                 // Trait impl: take implied bounds from all types that
965                 // appear in the trait reference.
966                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
967                 trait_ref.substs.types().collect()
968             }
969
970             None => {
971                 // Inherent impl: take implied bounds from the self type.
972                 let self_ty = self.tcx.type_of(impl_def_id);
973                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
974                 vec![self_ty]
975             }
976         }
977     }
978 }
979
980 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
981                        -> DiagnosticBuilder<'tcx> {
982     let mut err = struct_span_err!(tcx.sess, span, E0392,
983                   "parameter `{}` is never used", param_name);
984     err.span_label(span, "unused type parameter");
985     err
986 }
987
988 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: &str) {
989     struct_span_err!(tcx.sess, span, E0194,
990               "type parameter `{}` shadows another type parameter of the same name",
991               name)
992         .span_label(span, "shadows another type parameter")
993         .span_label(trait_decl_span, format!("first `{}` declared here", name))
994         .emit();
995 }