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