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