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