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