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