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