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