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