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