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