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