]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/wfcheck.rs
Use () for all_traits.
[rust.git] / compiler / rustc_typeck / src / check / wfcheck.rs
1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
3
4 use rustc_ast as ast;
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
7 use rustc_hir as hir;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_hir::intravisit as hir_visit;
10 use rustc_hir::intravisit::Visitor;
11 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
12 use rustc_hir::lang_items::LangItem;
13 use rustc_hir::ItemKind;
14 use rustc_middle::hir::map as hir_map;
15 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
16 use rustc_middle::ty::trait_def::TraitSpecializationKind;
17 use rustc_middle::ty::{
18     self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
19 };
20 use rustc_session::parse::feature_err;
21 use rustc_span::symbol::{sym, Ident, Symbol};
22 use rustc_span::Span;
23 use rustc_trait_selection::opaque_types::may_define_opaque_type;
24 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
25 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
26
27 use std::iter;
28 use std::ops::ControlFlow;
29
30 /// Helper type of a temporary returned by `.for_item(...)`.
31 /// This is necessary because we can't write the following bound:
32 ///
33 /// ```rust
34 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
35 /// ```
36 struct CheckWfFcxBuilder<'tcx> {
37     inherited: super::InheritedBuilder<'tcx>,
38     id: hir::HirId,
39     span: Span,
40     param_env: ty::ParamEnv<'tcx>,
41 }
42
43 impl<'tcx> CheckWfFcxBuilder<'tcx> {
44     fn with_fcx<F>(&mut self, f: F)
45     where
46         F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>) -> Vec<Ty<'tcx>>,
47     {
48         let id = self.id;
49         let span = self.span;
50         let param_env = self.param_env;
51         self.inherited.enter(|inh| {
52             let fcx = FnCtxt::new(&inh, param_env, id);
53             if !inh.tcx.features().trivial_bounds {
54                 // As predicates are cached rather than obligations, this
55                 // needs to be called first so that they are checked with an
56                 // empty `param_env`.
57                 check_false_global_bounds(&fcx, span, id);
58             }
59             let wf_tys = f(&fcx);
60             fcx.select_all_obligations_or_error();
61             fcx.regionck_item(id, span, &wf_tys);
62         });
63     }
64 }
65
66 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
67 /// well-formed, meaning that they do not require any constraints not declared in the struct
68 /// definition itself. For example, this definition would be illegal:
69 ///
70 /// ```rust
71 /// struct Ref<'a, T> { x: &'a T }
72 /// ```
73 ///
74 /// because the type did not declare that `T:'a`.
75 ///
76 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
77 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
78 /// the types first.
79 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
80     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
81     let item = tcx.hir().expect_item(hir_id);
82
83     debug!(
84         "check_item_well_formed(it.def_id={:?}, it.name={})",
85         item.def_id,
86         tcx.def_path_str(def_id.to_def_id())
87     );
88
89     match item.kind {
90         // Right now we check that every default trait implementation
91         // has an implementation of itself. Basically, a case like:
92         //
93         //     impl Trait for T {}
94         //
95         // has a requirement of `T: Trait` which was required for default
96         // method implementations. Although this could be improved now that
97         // there's a better infrastructure in place for this, it's being left
98         // for a follow-up work.
99         //
100         // Since there's such a requirement, we need to check *just* positive
101         // implementations, otherwise things like:
102         //
103         //     impl !Send for T {}
104         //
105         // won't be allowed unless there's an *explicit* implementation of `Send`
106         // for `T`
107         hir::ItemKind::Impl(ref impl_) => {
108             let is_auto = tcx
109                 .impl_trait_ref(item.def_id)
110                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
111             if let (hir::Defaultness::Default { .. }, true) = (impl_.defaultness, is_auto) {
112                 let sp = impl_.of_trait.as_ref().map_or(item.span, |t| t.path.span);
113                 let mut err =
114                     tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
115                 err.span_labels(impl_.defaultness_span, "default because of this");
116                 err.span_label(sp, "auto trait");
117                 err.emit();
118             }
119             // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
120             match (tcx.impl_polarity(def_id), impl_.polarity) {
121                 (ty::ImplPolarity::Positive, _) => {
122                     check_impl(tcx, item, impl_.self_ty, &impl_.of_trait);
123                 }
124                 (ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
125                     // FIXME(#27579): what amount of WF checking do we need for neg impls?
126                     if let hir::Defaultness::Default { .. } = impl_.defaultness {
127                         let mut spans = vec![span];
128                         spans.extend(impl_.defaultness_span);
129                         struct_span_err!(
130                             tcx.sess,
131                             spans,
132                             E0750,
133                             "negative impls cannot be default impls"
134                         )
135                         .emit();
136                     }
137                 }
138                 (ty::ImplPolarity::Reservation, _) => {
139                     // FIXME: what amount of WF checking do we need for reservation impls?
140                 }
141                 _ => unreachable!(),
142             }
143         }
144         hir::ItemKind::Fn(ref sig, ..) => {
145             check_item_fn(tcx, item.hir_id(), item.ident, item.span, sig.decl);
146         }
147         hir::ItemKind::Static(ref ty, ..) => {
148             check_item_type(tcx, item.hir_id(), ty.span, false);
149         }
150         hir::ItemKind::Const(ref ty, ..) => {
151             check_item_type(tcx, item.hir_id(), ty.span, false);
152         }
153         hir::ItemKind::ForeignMod { items, .. } => {
154             for it in items.iter() {
155                 let it = tcx.hir().foreign_item(it.id);
156                 match it.kind {
157                     hir::ForeignItemKind::Fn(ref decl, ..) => {
158                         check_item_fn(tcx, it.hir_id(), it.ident, it.span, decl)
159                     }
160                     hir::ForeignItemKind::Static(ref ty, ..) => {
161                         check_item_type(tcx, it.hir_id(), ty.span, true)
162                     }
163                     hir::ForeignItemKind::Type => (),
164                 }
165             }
166         }
167         hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
168             check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
169
170             check_variances_for_type_defn(tcx, item, ast_generics);
171         }
172         hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
173             check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
174
175             check_variances_for_type_defn(tcx, item, ast_generics);
176         }
177         hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
178             check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
179
180             check_variances_for_type_defn(tcx, item, ast_generics);
181         }
182         hir::ItemKind::Trait(..) => {
183             check_trait(tcx, item);
184         }
185         hir::ItemKind::TraitAlias(..) => {
186             check_trait(tcx, item);
187         }
188         _ => {}
189     }
190 }
191
192 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
193     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
194     let trait_item = tcx.hir().expect_trait_item(hir_id);
195
196     let method_sig = match trait_item.kind {
197         hir::TraitItemKind::Fn(ref sig, _) => Some(sig),
198         _ => None,
199     };
200     check_object_unsafe_self_trait_by_name(tcx, &trait_item);
201     check_associated_item(tcx, trait_item.hir_id(), trait_item.span, method_sig);
202 }
203
204 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
205     match ty.kind {
206         hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
207             [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
208             _ => false,
209         },
210         _ => false,
211     }
212 }
213
214 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
215 /// When this is done, suggest using `Self` instead.
216 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
217     let (trait_name, trait_def_id) = match tcx.hir().get(tcx.hir().get_parent_item(item.hir_id())) {
218         hir::Node::Item(item) => match item.kind {
219             hir::ItemKind::Trait(..) => (item.ident, item.def_id),
220             _ => return,
221         },
222         _ => return,
223     };
224     let mut trait_should_be_self = vec![];
225     match &item.kind {
226         hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
227             if could_be_self(trait_def_id, ty) =>
228         {
229             trait_should_be_self.push(ty.span)
230         }
231         hir::TraitItemKind::Fn(sig, _) => {
232             for ty in sig.decl.inputs {
233                 if could_be_self(trait_def_id, ty) {
234                     trait_should_be_self.push(ty.span);
235                 }
236             }
237             match sig.decl.output {
238                 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
239                     trait_should_be_self.push(ty.span);
240                 }
241                 _ => {}
242             }
243         }
244         _ => {}
245     }
246     if !trait_should_be_self.is_empty() {
247         if tcx.object_safety_violations(trait_def_id).is_empty() {
248             return;
249         }
250         let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
251         tcx.sess
252             .struct_span_err(
253                 trait_should_be_self,
254                 "associated item referring to unboxed trait object for its own trait",
255             )
256             .span_label(trait_name.span, "in this trait")
257             .multipart_suggestion(
258                 "you might have meant to use `Self` to refer to the implementing type",
259                 sugg,
260                 Applicability::MachineApplicable,
261             )
262             .emit();
263     }
264 }
265
266 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
267     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
268     let impl_item = tcx.hir().expect_impl_item(hir_id);
269
270     let method_sig = match impl_item.kind {
271         hir::ImplItemKind::Fn(ref sig, _) => Some(sig),
272         _ => None,
273     };
274
275     check_associated_item(tcx, impl_item.hir_id(), impl_item.span, method_sig);
276 }
277
278 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
279     match param.kind {
280         // We currently only check wf of const params here.
281         hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
282
283         // Const parameters are well formed if their type is structural match.
284         // FIXME(const_generics_defaults): we also need to check that the `default` is wf.
285         hir::GenericParamKind::Const { ty: hir_ty, default: _ } => {
286             let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
287
288             let err_ty_str;
289             let mut is_ptr = true;
290             let err = if tcx.features().const_generics {
291                 match ty.peel_refs().kind() {
292                     ty::FnPtr(_) => Some("function pointers"),
293                     ty::RawPtr(_) => Some("raw pointers"),
294                     _ => None,
295                 }
296             } else {
297                 match ty.kind() {
298                     ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
299                     ty::FnPtr(_) => Some("function pointers"),
300                     ty::RawPtr(_) => Some("raw pointers"),
301                     _ => {
302                         is_ptr = false;
303                         err_ty_str = format!("`{}`", ty);
304                         Some(err_ty_str.as_str())
305                     }
306                 }
307             };
308             if let Some(unsupported_type) = err {
309                 if is_ptr {
310                     tcx.sess.span_err(
311                         hir_ty.span,
312                         &format!(
313                             "using {} as const generic parameters is forbidden",
314                             unsupported_type
315                         ),
316                     )
317                 } else {
318                     let mut err = tcx.sess.struct_span_err(
319                         hir_ty.span,
320                         &format!(
321                             "{} is forbidden as the type of a const generic parameter",
322                             unsupported_type
323                         ),
324                     );
325                     err.note("the only supported types are integers, `bool` and `char`");
326                     if tcx.sess.is_nightly_build() {
327                         err.help(
328                             "more complex types are supported with `#![feature(const_generics)]`",
329                         );
330                     }
331                     err.emit()
332                 }
333             };
334
335             if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
336                 .is_some()
337             {
338                 // We use the same error code in both branches, because this is really the same
339                 // issue: we just special-case the message for type parameters to make it
340                 // clearer.
341                 if let ty::Param(_) = ty.peel_refs().kind() {
342                     // Const parameters may not have type parameters as their types,
343                     // because we cannot be sure that the type parameter derives `PartialEq`
344                     // and `Eq` (just implementing them is not enough for `structural_match`).
345                     struct_span_err!(
346                         tcx.sess,
347                         hir_ty.span,
348                         E0741,
349                         "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
350                             used as the type of a const parameter",
351                         ty,
352                     )
353                     .span_label(
354                         hir_ty.span,
355                         format!("`{}` may not derive both `PartialEq` and `Eq`", ty),
356                     )
357                     .note(
358                         "it is not currently possible to use a type parameter as the type of a \
359                             const parameter",
360                     )
361                     .emit();
362                 } else {
363                     struct_span_err!(
364                         tcx.sess,
365                         hir_ty.span,
366                         E0741,
367                         "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
368                             the type of a const parameter",
369                         ty,
370                     )
371                     .span_label(
372                         hir_ty.span,
373                         format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
374                     )
375                     .emit();
376                 }
377             }
378         }
379     }
380 }
381
382 fn check_associated_item(
383     tcx: TyCtxt<'_>,
384     item_id: hir::HirId,
385     span: Span,
386     sig_if_method: Option<&hir::FnSig<'_>>,
387 ) {
388     debug!("check_associated_item: {:?}", item_id);
389
390     let code = ObligationCauseCode::MiscObligation;
391     for_id(tcx, item_id, span).with_fcx(|fcx| {
392         let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
393
394         let (mut implied_bounds, self_ty) = match item.container {
395             ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
396             ty::ImplContainer(def_id) => {
397                 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
398             }
399         };
400
401         match item.kind {
402             ty::AssocKind::Const => {
403                 let ty = fcx.tcx.type_of(item.def_id);
404                 let ty = fcx.normalize_associated_types_in(span, ty);
405                 fcx.register_wf_obligation(ty.into(), span, code.clone());
406             }
407             ty::AssocKind::Fn => {
408                 let sig = fcx.tcx.fn_sig(item.def_id);
409                 let sig = fcx.normalize_associated_types_in(span, sig);
410                 let hir_sig = sig_if_method.expect("bad signature for method");
411                 check_fn_or_method(
412                     fcx,
413                     item.ident.span,
414                     sig,
415                     hir_sig.decl,
416                     item.def_id,
417                     &mut implied_bounds,
418                 );
419                 check_method_receiver(fcx, hir_sig, &item, self_ty);
420             }
421             ty::AssocKind::Type => {
422                 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
423                     check_associated_type_bounds(fcx, item, span)
424                 }
425                 if item.defaultness.has_value() {
426                     let ty = fcx.tcx.type_of(item.def_id);
427                     let ty = fcx.normalize_associated_types_in(span, ty);
428                     fcx.register_wf_obligation(ty.into(), span, code.clone());
429                 }
430             }
431         }
432
433         implied_bounds
434     })
435 }
436
437 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
438     for_id(tcx, item.hir_id(), item.span)
439 }
440
441 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
442     let def_id = tcx.hir().local_def_id(id);
443     CheckWfFcxBuilder {
444         inherited: Inherited::build(tcx, def_id),
445         id,
446         span,
447         param_env: tcx.param_env(def_id),
448     }
449 }
450
451 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
452     match kind {
453         ItemKind::Struct(..) => Some(AdtKind::Struct),
454         ItemKind::Union(..) => Some(AdtKind::Union),
455         ItemKind::Enum(..) => Some(AdtKind::Enum),
456         _ => None,
457     }
458 }
459
460 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
461 fn check_type_defn<'tcx, F>(
462     tcx: TyCtxt<'tcx>,
463     item: &hir::Item<'tcx>,
464     all_sized: bool,
465     mut lookup_fields: F,
466 ) where
467     F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
468 {
469     for_item(tcx, item).with_fcx(|fcx| {
470         let variants = lookup_fields(fcx);
471         let packed = tcx.adt_def(item.def_id).repr.packed();
472
473         for variant in &variants {
474             // For DST, or when drop needs to copy things around, all
475             // intermediate types must be sized.
476             let needs_drop_copy = || {
477                 packed && {
478                     let ty = variant.fields.last().unwrap().ty;
479                     let ty = tcx.erase_regions(ty);
480                     if ty.needs_infer() {
481                         tcx.sess
482                             .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
483                         // Just treat unresolved type expression as if it needs drop.
484                         true
485                     } else {
486                         ty.needs_drop(tcx, tcx.param_env(item.def_id))
487                     }
488                 }
489             };
490             let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
491             let unsized_len = if all_sized { 0 } else { 1 };
492             for (idx, field) in
493                 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
494             {
495                 let last = idx == variant.fields.len() - 1;
496                 fcx.register_bound(
497                     field.ty,
498                     tcx.require_lang_item(LangItem::Sized, None),
499                     traits::ObligationCause::new(
500                         field.span,
501                         fcx.body_id,
502                         traits::FieldSized {
503                             adt_kind: match item_adt_kind(&item.kind) {
504                                 Some(i) => i,
505                                 None => bug!(),
506                             },
507                             span: field.span,
508                             last,
509                         },
510                     ),
511                 );
512             }
513
514             // All field types must be well-formed.
515             for field in &variant.fields {
516                 fcx.register_wf_obligation(
517                     field.ty.into(),
518                     field.span,
519                     ObligationCauseCode::MiscObligation,
520                 )
521             }
522
523             // Explicit `enum` discriminant values must const-evaluate successfully.
524             if let Some(discr_def_id) = variant.explicit_discr {
525                 let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
526
527                 let cause = traits::ObligationCause::new(
528                     tcx.def_span(discr_def_id),
529                     fcx.body_id,
530                     traits::MiscObligation,
531                 );
532                 fcx.register_predicate(traits::Obligation::new(
533                     cause,
534                     fcx.param_env,
535                     ty::PredicateKind::ConstEvaluatable(
536                         ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
537                         discr_substs,
538                     )
539                     .to_predicate(tcx),
540                 ));
541             }
542         }
543
544         check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
545
546         // No implied bounds in a struct definition.
547         vec![]
548     });
549 }
550
551 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
552     debug!("check_trait: {:?}", item.def_id);
553
554     let trait_def = tcx.trait_def(item.def_id);
555     if trait_def.is_marker
556         || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
557     {
558         for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
559             struct_span_err!(
560                 tcx.sess,
561                 tcx.def_span(*associated_def_id),
562                 E0714,
563                 "marker traits cannot have associated items",
564             )
565             .emit();
566         }
567     }
568
569     // FIXME: this shouldn't use an `FnCtxt` at all.
570     for_item(tcx, item).with_fcx(|fcx| {
571         check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
572
573         vec![]
574     });
575 }
576
577 /// Checks all associated type defaults of trait `trait_def_id`.
578 ///
579 /// Assuming the defaults are used, check that all predicates (bounds on the
580 /// assoc type and where clauses on the trait) hold.
581 fn check_associated_type_bounds(fcx: &FnCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
582     let tcx = fcx.tcx;
583
584     let bounds = tcx.explicit_item_bounds(item.def_id);
585
586     debug!("check_associated_type_bounds: bounds={:?}", bounds);
587     let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
588         let normalized_bound = fcx.normalize_associated_types_in(span, bound);
589         traits::wf::predicate_obligations(
590             fcx,
591             fcx.param_env,
592             fcx.body_id,
593             normalized_bound,
594             bound_span,
595         )
596     });
597
598     for obligation in wf_obligations {
599         debug!("next obligation cause: {:?}", obligation.cause);
600         fcx.register_predicate(obligation);
601     }
602 }
603
604 fn check_item_fn(
605     tcx: TyCtxt<'_>,
606     item_id: hir::HirId,
607     ident: Ident,
608     span: Span,
609     decl: &hir::FnDecl<'_>,
610 ) {
611     for_id(tcx, item_id, span).with_fcx(|fcx| {
612         let def_id = tcx.hir().local_def_id(item_id);
613         let sig = tcx.fn_sig(def_id);
614         let sig = fcx.normalize_associated_types_in(span, sig);
615         let mut implied_bounds = vec![];
616         check_fn_or_method(fcx, ident.span, sig, decl, def_id.to_def_id(), &mut implied_bounds);
617         implied_bounds
618     })
619 }
620
621 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
622     debug!("check_item_type: {:?}", item_id);
623
624     for_id(tcx, item_id, ty_span).with_fcx(|fcx| {
625         let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
626         let item_ty = fcx.normalize_associated_types_in(ty_span, ty);
627
628         let mut forbid_unsized = true;
629         if allow_foreign_ty {
630             let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
631             if let ty::Foreign(_) = tail.kind() {
632                 forbid_unsized = false;
633             }
634         }
635
636         fcx.register_wf_obligation(item_ty.into(), ty_span, ObligationCauseCode::MiscObligation);
637         if forbid_unsized {
638             fcx.register_bound(
639                 item_ty,
640                 tcx.require_lang_item(LangItem::Sized, None),
641                 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
642             );
643         }
644
645         // No implied bounds in a const, etc.
646         vec![]
647     });
648 }
649
650 fn check_impl<'tcx>(
651     tcx: TyCtxt<'tcx>,
652     item: &'tcx hir::Item<'tcx>,
653     ast_self_ty: &hir::Ty<'_>,
654     ast_trait_ref: &Option<hir::TraitRef<'_>>,
655 ) {
656     debug!("check_impl: {:?}", item);
657
658     for_item(tcx, item).with_fcx(|fcx| {
659         match *ast_trait_ref {
660             Some(ref ast_trait_ref) => {
661                 // `#[rustc_reservation_impl]` impls are not real impls and
662                 // therefore don't need to be WF (the trait's `Self: Trait` predicate
663                 // won't hold).
664                 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
665                 let trait_ref =
666                     fcx.normalize_associated_types_in(ast_trait_ref.path.span, trait_ref);
667                 let obligations = traits::wf::trait_obligations(
668                     fcx,
669                     fcx.param_env,
670                     fcx.body_id,
671                     &trait_ref,
672                     ast_trait_ref.path.span,
673                     Some(item),
674                 );
675                 for obligation in obligations {
676                     fcx.register_predicate(obligation);
677                 }
678             }
679             None => {
680                 let self_ty = tcx.type_of(item.def_id);
681                 let self_ty = fcx.normalize_associated_types_in(item.span, self_ty);
682                 fcx.register_wf_obligation(
683                     self_ty.into(),
684                     ast_self_ty.span,
685                     ObligationCauseCode::MiscObligation,
686                 );
687             }
688         }
689
690         check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
691
692         fcx.impl_implied_bounds(item.def_id.to_def_id(), item.span)
693     });
694 }
695
696 /// Checks where-clauses and inline bounds that are declared on `def_id`.
697 fn check_where_clauses<'tcx, 'fcx>(
698     fcx: &FnCtxt<'fcx, 'tcx>,
699     span: Span,
700     def_id: DefId,
701     return_ty: Option<(Ty<'tcx>, Span)>,
702 ) {
703     debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
704     let tcx = fcx.tcx;
705
706     let predicates = tcx.predicates_of(def_id);
707     let generics = tcx.generics_of(def_id);
708
709     let is_our_default = |def: &ty::GenericParamDef| match def.kind {
710         GenericParamDefKind::Type { has_default, .. }
711         | GenericParamDefKind::Const { has_default } => {
712             has_default && def.index >= generics.parent_count as u32
713         }
714         GenericParamDefKind::Lifetime => unreachable!(),
715     };
716
717     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
718     // For example, this forbids the declaration:
719     //
720     //     struct Foo<T = Vec<[u32]>> { .. }
721     //
722     // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
723     for param in &generics.params {
724         match param.kind {
725             GenericParamDefKind::Type { .. } => {
726                 if is_our_default(&param) {
727                     let ty = tcx.type_of(param.def_id);
728                     // Ignore dependent defaults -- that is, where the default of one type
729                     // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
730                     // be sure if it will error or not as user might always specify the other.
731                     if !ty.needs_subst() {
732                         fcx.register_wf_obligation(
733                             ty.into(),
734                             tcx.def_span(param.def_id),
735                             ObligationCauseCode::MiscObligation,
736                         );
737                     }
738                 }
739             }
740             GenericParamDefKind::Const { .. } => {
741                 // FIXME(const_generics_defaults): Figure out if this
742                 // is the behavior we want, see the comment further below.
743                 if is_our_default(&param) {
744                     let default_ct = tcx.const_param_default(param.def_id);
745                     fcx.register_wf_obligation(
746                         default_ct.into(),
747                         tcx.def_span(param.def_id),
748                         ObligationCauseCode::MiscObligation,
749                     );
750                 }
751             }
752             // Doesn't have defaults.
753             GenericParamDefKind::Lifetime => {}
754         }
755     }
756
757     // Check that trait predicates are WF when params are substituted by their defaults.
758     // We don't want to overly constrain the predicates that may be written but we want to
759     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
760     // Therefore we check if a predicate which contains a single type param
761     // with a concrete default is WF with that default substituted.
762     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
763     //
764     // First we build the defaulted substitution.
765     let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
766         match param.kind {
767             GenericParamDefKind::Lifetime => {
768                 // All regions are identity.
769                 tcx.mk_param_from_def(param)
770             }
771
772             GenericParamDefKind::Type { .. } => {
773                 // If the param has a default, ...
774                 if is_our_default(param) {
775                     let default_ty = tcx.type_of(param.def_id);
776                     // ... and it's not a dependent default, ...
777                     if !default_ty.needs_subst() {
778                         // ... then substitute it with the default.
779                         return default_ty.into();
780                     }
781                 }
782
783                 tcx.mk_param_from_def(param)
784             }
785             GenericParamDefKind::Const { .. } => {
786                 // FIXME(const_generics_defaults): I(@lcnr) feel like always
787                 // using the const parameter is the right choice here, even
788                 // if it needs substs.
789                 //
790                 // Before stabilizing this we probably want to get some tests
791                 // where this makes a difference and figure out what's the exact
792                 // behavior we want here.
793
794                 // If the param has a default, ...
795                 if is_our_default(param) {
796                     let default_ct = tcx.const_param_default(param.def_id);
797                     // ... and it's not a dependent default, ...
798                     if !default_ct.needs_subst() {
799                         // ... then substitute it with the default.
800                         return default_ct.into();
801                     }
802                 }
803
804                 tcx.mk_param_from_def(param)
805             }
806         }
807     });
808
809     // Now we build the substituted predicates.
810     let default_obligations = predicates
811         .predicates
812         .iter()
813         .flat_map(|&(pred, sp)| {
814             #[derive(Default)]
815             struct CountParams {
816                 params: FxHashSet<u32>,
817             }
818             impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
819                 type BreakTy = ();
820
821                 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
822                     if let ty::Param(param) = t.kind() {
823                         self.params.insert(param.index);
824                     }
825                     t.super_visit_with(self)
826                 }
827
828                 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
829                     ControlFlow::BREAK
830                 }
831
832                 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
833                     if let ty::ConstKind::Param(param) = c.val {
834                         self.params.insert(param.index);
835                     }
836                     c.super_visit_with(self)
837                 }
838             }
839             let mut param_count = CountParams::default();
840             let has_region = pred.visit_with(&mut param_count).is_break();
841             let substituted_pred = pred.subst(tcx, substs);
842             // Don't check non-defaulted params, dependent defaults (including lifetimes)
843             // or preds with multiple params.
844             if substituted_pred.has_param_types_or_consts()
845                 || param_count.params.len() > 1
846                 || has_region
847             {
848                 None
849             } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
850                 // Avoid duplication of predicates that contain no parameters, for example.
851                 None
852             } else {
853                 Some((substituted_pred, sp))
854             }
855         })
856         .map(|(pred, sp)| {
857             // Convert each of those into an obligation. So if you have
858             // something like `struct Foo<T: Copy = String>`, we would
859             // take that predicate `T: Copy`, substitute to `String: Copy`
860             // (actually that happens in the previous `flat_map` call),
861             // and then try to prove it (in this case, we'll fail).
862             //
863             // Note the subtle difference from how we handle `predicates`
864             // below: there, we are not trying to prove those predicates
865             // to be *true* but merely *well-formed*.
866             let pred = fcx.normalize_associated_types_in(sp, pred);
867             let cause =
868                 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
869             traits::Obligation::new(cause, fcx.param_env, pred)
870         });
871
872     let predicates = predicates.instantiate_identity(tcx);
873
874     if let Some((mut return_ty, span)) = return_ty {
875         if return_ty.has_infer_types_or_consts() {
876             fcx.select_obligations_where_possible(false, |_| {});
877             return_ty = fcx.resolve_vars_if_possible(return_ty);
878         }
879         check_opaque_types(fcx, def_id.expect_local(), span, return_ty);
880     }
881
882     let predicates = fcx.normalize_associated_types_in(span, predicates);
883
884     debug!("check_where_clauses: predicates={:?}", predicates.predicates);
885     assert_eq!(predicates.predicates.len(), predicates.spans.len());
886     let wf_obligations =
887         iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
888             traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, sp)
889         });
890
891     for obligation in wf_obligations.chain(default_obligations) {
892         debug!("next obligation cause: {:?}", obligation.cause);
893         fcx.register_predicate(obligation);
894     }
895 }
896
897 fn check_fn_or_method<'fcx, 'tcx>(
898     fcx: &FnCtxt<'fcx, 'tcx>,
899     span: Span,
900     sig: ty::PolyFnSig<'tcx>,
901     hir_decl: &hir::FnDecl<'_>,
902     def_id: DefId,
903     implied_bounds: &mut Vec<Ty<'tcx>>,
904 ) {
905     let sig = fcx.normalize_associated_types_in(span, sig);
906     let sig = fcx.tcx.liberate_late_bound_regions(def_id, sig);
907
908     for (&input_ty, ty) in iter::zip(sig.inputs(), hir_decl.inputs) {
909         fcx.register_wf_obligation(input_ty.into(), ty.span, ObligationCauseCode::MiscObligation);
910     }
911     implied_bounds.extend(sig.inputs());
912
913     fcx.register_wf_obligation(
914         sig.output().into(),
915         hir_decl.output.span(),
916         ObligationCauseCode::ReturnType,
917     );
918
919     // FIXME(#25759) return types should not be implied bounds
920     implied_bounds.push(sig.output());
921
922     check_where_clauses(fcx, span, def_id, Some((sig.output(), hir_decl.output.span())));
923 }
924
925 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
926 /// laid for "higher-order pattern unification".
927 /// This ensures that inference is tractable.
928 /// In particular, definitions of opaque types can only use other generics as arguments,
929 /// and they cannot repeat an argument. Example:
930 ///
931 /// ```rust
932 /// type Foo<A, B> = impl Bar<A, B>;
933 ///
934 /// // Okay -- `Foo` is applied to two distinct, generic types.
935 /// fn a<T, U>() -> Foo<T, U> { .. }
936 ///
937 /// // Not okay -- `Foo` is applied to `T` twice.
938 /// fn b<T>() -> Foo<T, T> { .. }
939 ///
940 /// // Not okay -- `Foo` is applied to a non-generic type.
941 /// fn b<T>() -> Foo<T, u32> { .. }
942 /// ```
943 ///
944 fn check_opaque_types<'fcx, 'tcx>(
945     fcx: &FnCtxt<'fcx, 'tcx>,
946     fn_def_id: LocalDefId,
947     span: Span,
948     ty: Ty<'tcx>,
949 ) {
950     trace!("check_opaque_types(fn_def_id={:?}, ty={:?})", fn_def_id, ty);
951     let tcx = fcx.tcx;
952
953     ty.fold_with(&mut ty::fold::BottomUpFolder {
954         tcx,
955         ty_op: |ty| {
956             if let ty::Opaque(def_id, substs) = *ty.kind() {
957                 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
958                 let generics = tcx.generics_of(def_id);
959
960                 let opaque_hir_id = if let Some(local_id) = def_id.as_local() {
961                     tcx.hir().local_def_id_to_hir_id(local_id)
962                 } else {
963                     // Opaque types from other crates won't have defining uses in this crate.
964                     return ty;
965                 };
966                 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) =
967                     tcx.hir().expect_item(opaque_hir_id).kind
968                 {
969                     // No need to check return position impl trait (RPIT)
970                     // because for type and const parameters they are correct
971                     // by construction: we convert
972                     //
973                     // fn foo<P0..Pn>() -> impl Trait
974                     //
975                     // into
976                     //
977                     // type Foo<P0...Pn>
978                     // fn foo<P0..Pn>() -> Foo<P0...Pn>.
979                     //
980                     // For lifetime parameters we convert
981                     //
982                     // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
983                     //
984                     // into
985                     //
986                     // type foo::<'p0..'pn>::Foo<'q0..'qm>
987                     // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
988                     //
989                     // which would error here on all of the `'static` args.
990                     return ty;
991                 }
992                 if !may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
993                     return ty;
994                 }
995                 trace!("check_opaque_types: may define, generics={:#?}", generics);
996                 let mut seen_params: FxHashMap<_, Vec<_>> = FxHashMap::default();
997                 for (i, arg) in substs.iter().enumerate() {
998                     let arg_is_param = match arg.unpack() {
999                         GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)),
1000
1001                         GenericArgKind::Lifetime(region) => {
1002                             if let ty::ReStatic = region {
1003                                 tcx.sess
1004                                     .struct_span_err(
1005                                         span,
1006                                         "non-defining opaque type use in defining scope",
1007                                     )
1008                                     .span_label(
1009                                         tcx.def_span(generics.param_at(i, tcx).def_id),
1010                                         "cannot use static lifetime; use a bound lifetime \
1011                                                  instead or remove the lifetime parameter from the \
1012                                                  opaque type",
1013                                     )
1014                                     .emit();
1015                                 continue;
1016                             }
1017
1018                             true
1019                         }
1020
1021                         GenericArgKind::Const(ct) => matches!(ct.val, ty::ConstKind::Param(_)),
1022                     };
1023
1024                     if arg_is_param {
1025                         seen_params.entry(arg).or_default().push(i);
1026                     } else {
1027                         // Prevent `fn foo() -> Foo<u32>` from being defining.
1028                         let opaque_param = generics.param_at(i, tcx);
1029                         tcx.sess
1030                             .struct_span_err(span, "non-defining opaque type use in defining scope")
1031                             .span_note(
1032                                 tcx.def_span(opaque_param.def_id),
1033                                 &format!(
1034                                     "used non-generic {} `{}` for generic parameter",
1035                                     opaque_param.kind.descr(),
1036                                     arg,
1037                                 ),
1038                             )
1039                             .emit();
1040                     }
1041                 } // for (arg, param)
1042
1043                 for (_, indices) in seen_params {
1044                     if indices.len() > 1 {
1045                         let descr = generics.param_at(indices[0], tcx).kind.descr();
1046                         let spans: Vec<_> = indices
1047                             .into_iter()
1048                             .map(|i| tcx.def_span(generics.param_at(i, tcx).def_id))
1049                             .collect();
1050                         tcx.sess
1051                             .struct_span_err(span, "non-defining opaque type use in defining scope")
1052                             .span_note(spans, &format!("{} used multiple times", descr))
1053                             .emit();
1054                     }
1055                 }
1056             } // if let Opaque
1057             ty
1058         },
1059         lt_op: |lt| lt,
1060         ct_op: |ct| ct,
1061     });
1062 }
1063
1064 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1065      `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1066      of the previous types except `Self`)";
1067
1068 fn check_method_receiver<'fcx, 'tcx>(
1069     fcx: &FnCtxt<'fcx, 'tcx>,
1070     fn_sig: &hir::FnSig<'_>,
1071     method: &ty::AssocItem,
1072     self_ty: Ty<'tcx>,
1073 ) {
1074     // Check that the method has a valid receiver type, given the type `Self`.
1075     debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
1076
1077     if !method.fn_has_self_parameter {
1078         return;
1079     }
1080
1081     let span = fn_sig.decl.inputs[0].span;
1082
1083     let sig = fcx.tcx.fn_sig(method.def_id);
1084     let sig = fcx.normalize_associated_types_in(span, sig);
1085     let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, sig);
1086
1087     debug!("check_method_receiver: sig={:?}", sig);
1088
1089     let self_ty = fcx.normalize_associated_types_in(span, self_ty);
1090     let self_ty =
1091         fcx.tcx.liberate_late_bound_regions(method.def_id, ty::Binder::bind(self_ty, fcx.tcx));
1092
1093     let receiver_ty = sig.inputs()[0];
1094
1095     let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
1096     let receiver_ty =
1097         fcx.tcx.liberate_late_bound_regions(method.def_id, ty::Binder::bind(receiver_ty, fcx.tcx));
1098
1099     if fcx.tcx.features().arbitrary_self_types {
1100         if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1101             // Report error; `arbitrary_self_types` was enabled.
1102             e0307(fcx, span, receiver_ty);
1103         }
1104     } else {
1105         if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1106             if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1107                 // Report error; would have worked with `arbitrary_self_types`.
1108                 feature_err(
1109                     &fcx.tcx.sess.parse_sess,
1110                     sym::arbitrary_self_types,
1111                     span,
1112                     &format!(
1113                         "`{}` cannot be used as the type of `self` without \
1114                          the `arbitrary_self_types` feature",
1115                         receiver_ty,
1116                     ),
1117                 )
1118                 .help(HELP_FOR_SELF_TYPE)
1119                 .emit();
1120             } else {
1121                 // Report error; would not have worked with `arbitrary_self_types`.
1122                 e0307(fcx, span, receiver_ty);
1123             }
1124         }
1125     }
1126 }
1127
1128 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1129     struct_span_err!(
1130         fcx.tcx.sess.diagnostic(),
1131         span,
1132         E0307,
1133         "invalid `self` parameter type: {}",
1134         receiver_ty,
1135     )
1136     .note("type of `self` must be `Self` or a type that dereferences to it")
1137     .help(HELP_FOR_SELF_TYPE)
1138     .emit();
1139 }
1140
1141 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1142 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1143 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1144 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1145 /// `Deref<Target = self_ty>`.
1146 ///
1147 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1148 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1149 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1150 fn receiver_is_valid<'fcx, 'tcx>(
1151     fcx: &FnCtxt<'fcx, 'tcx>,
1152     span: Span,
1153     receiver_ty: Ty<'tcx>,
1154     self_ty: Ty<'tcx>,
1155     arbitrary_self_types_enabled: bool,
1156 ) -> bool {
1157     let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1158
1159     let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1160
1161     // `self: Self` is always valid.
1162     if can_eq_self(receiver_ty) {
1163         if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1164             err.emit();
1165         }
1166         return true;
1167     }
1168
1169     let mut autoderef = fcx.autoderef(span, receiver_ty);
1170
1171     // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1172     if arbitrary_self_types_enabled {
1173         autoderef = autoderef.include_raw_pointers();
1174     }
1175
1176     // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1177     autoderef.next();
1178
1179     let receiver_trait_def_id = fcx.tcx.require_lang_item(LangItem::Receiver, None);
1180
1181     // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1182     loop {
1183         if let Some((potential_self_ty, _)) = autoderef.next() {
1184             debug!(
1185                 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1186                 potential_self_ty, self_ty
1187             );
1188
1189             if can_eq_self(potential_self_ty) {
1190                 fcx.register_predicates(autoderef.into_obligations());
1191
1192                 if let Some(mut err) =
1193                     fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1194                 {
1195                     err.emit();
1196                 }
1197
1198                 break;
1199             } else {
1200                 // Without `feature(arbitrary_self_types)`, we require that each step in the
1201                 // deref chain implement `receiver`
1202                 if !arbitrary_self_types_enabled
1203                     && !receiver_is_implemented(
1204                         fcx,
1205                         receiver_trait_def_id,
1206                         cause.clone(),
1207                         potential_self_ty,
1208                     )
1209                 {
1210                     return false;
1211                 }
1212             }
1213         } else {
1214             debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1215             // If he receiver already has errors reported due to it, consider it valid to avoid
1216             // unnecessary errors (#58712).
1217             return receiver_ty.references_error();
1218         }
1219     }
1220
1221     // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1222     if !arbitrary_self_types_enabled
1223         && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1224     {
1225         return false;
1226     }
1227
1228     true
1229 }
1230
1231 fn receiver_is_implemented(
1232     fcx: &FnCtxt<'_, 'tcx>,
1233     receiver_trait_def_id: DefId,
1234     cause: ObligationCause<'tcx>,
1235     receiver_ty: Ty<'tcx>,
1236 ) -> bool {
1237     let trait_ref = ty::TraitRef {
1238         def_id: receiver_trait_def_id,
1239         substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1240     };
1241
1242     let obligation = traits::Obligation::new(
1243         cause,
1244         fcx.param_env,
1245         trait_ref.without_const().to_predicate(fcx.tcx),
1246     );
1247
1248     if fcx.predicate_must_hold_modulo_regions(&obligation) {
1249         true
1250     } else {
1251         debug!(
1252             "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1253             receiver_ty
1254         );
1255         false
1256     }
1257 }
1258
1259 fn check_variances_for_type_defn<'tcx>(
1260     tcx: TyCtxt<'tcx>,
1261     item: &hir::Item<'tcx>,
1262     hir_generics: &hir::Generics<'_>,
1263 ) {
1264     let ty = tcx.type_of(item.def_id);
1265     if tcx.has_error_field(ty) {
1266         return;
1267     }
1268
1269     let ty_predicates = tcx.predicates_of(item.def_id);
1270     assert_eq!(ty_predicates.parent, None);
1271     let variances = tcx.variances_of(item.def_id);
1272
1273     let mut constrained_parameters: FxHashSet<_> = variances
1274         .iter()
1275         .enumerate()
1276         .filter(|&(_, &variance)| variance != ty::Bivariant)
1277         .map(|(index, _)| Parameter(index as u32))
1278         .collect();
1279
1280     identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1281
1282     for (index, _) in variances.iter().enumerate() {
1283         if constrained_parameters.contains(&Parameter(index as u32)) {
1284             continue;
1285         }
1286
1287         let param = &hir_generics.params[index];
1288
1289         match param.name {
1290             hir::ParamName::Error => {}
1291             _ => report_bivariance(tcx, param),
1292         }
1293     }
1294 }
1295
1296 fn report_bivariance(tcx: TyCtxt<'_>, param: &rustc_hir::GenericParam<'_>) {
1297     let span = param.span;
1298     let param_name = param.name.ident().name;
1299     let mut err = error_392(tcx, span, param_name);
1300
1301     let suggested_marker_id = tcx.lang_items().phantom_data();
1302     // Help is available only in presence of lang items.
1303     let msg = if let Some(def_id) = suggested_marker_id {
1304         format!(
1305             "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1306             param_name,
1307             tcx.def_path_str(def_id),
1308         )
1309     } else {
1310         format!("consider removing `{}` or referring to it in a field", param_name)
1311     };
1312     err.help(&msg);
1313
1314     if matches!(param.kind, rustc_hir::GenericParamKind::Type { .. }) {
1315         err.help(&format!(
1316             "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1317             param_name
1318         ));
1319     }
1320     err.emit()
1321 }
1322
1323 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1324 /// aren't true.
1325 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1326     let empty_env = ty::ParamEnv::empty();
1327
1328     let def_id = fcx.tcx.hir().local_def_id(id);
1329     let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p);
1330     // Check elaborated bounds.
1331     let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1332
1333     for obligation in implied_obligations {
1334         let pred = obligation.predicate;
1335         // Match the existing behavior.
1336         if pred.is_global() && !pred.has_late_bound_regions() {
1337             let pred = fcx.normalize_associated_types_in(span, pred);
1338             let obligation = traits::Obligation::new(
1339                 traits::ObligationCause::new(span, id, traits::TrivialBound),
1340                 empty_env,
1341                 pred,
1342             );
1343             fcx.register_predicate(obligation);
1344         }
1345     }
1346
1347     fcx.select_all_obligations_or_error();
1348 }
1349
1350 #[derive(Clone, Copy)]
1351 pub struct CheckTypeWellFormedVisitor<'tcx> {
1352     tcx: TyCtxt<'tcx>,
1353 }
1354
1355 impl CheckTypeWellFormedVisitor<'tcx> {
1356     pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1357         CheckTypeWellFormedVisitor { tcx }
1358     }
1359 }
1360
1361 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1362     fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1363         Visitor::visit_item(&mut self.clone(), i);
1364     }
1365
1366     fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1367         Visitor::visit_trait_item(&mut self.clone(), trait_item);
1368     }
1369
1370     fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1371         Visitor::visit_impl_item(&mut self.clone(), impl_item);
1372     }
1373
1374     fn visit_foreign_item(&self, foreign_item: &'tcx hir::ForeignItem<'tcx>) {
1375         Visitor::visit_foreign_item(&mut self.clone(), foreign_item)
1376     }
1377 }
1378
1379 impl Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1380     type Map = hir_map::Map<'tcx>;
1381
1382     fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
1383         hir_visit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
1384     }
1385
1386     fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
1387         debug!("visit_item: {:?}", i);
1388         self.tcx.ensure().check_item_well_formed(i.def_id);
1389         hir_visit::walk_item(self, i);
1390     }
1391
1392     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1393         debug!("visit_trait_item: {:?}", trait_item);
1394         self.tcx.ensure().check_trait_item_well_formed(trait_item.def_id);
1395         hir_visit::walk_trait_item(self, trait_item);
1396     }
1397
1398     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1399         debug!("visit_impl_item: {:?}", impl_item);
1400         self.tcx.ensure().check_impl_item_well_formed(impl_item.def_id);
1401         hir_visit::walk_impl_item(self, impl_item);
1402     }
1403
1404     fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
1405         check_param_wf(self.tcx, p);
1406         hir_visit::walk_generic_param(self, p);
1407     }
1408 }
1409
1410 ///////////////////////////////////////////////////////////////////////////
1411 // ADT
1412
1413 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1414 struct AdtVariant<'tcx> {
1415     /// Types of fields in the variant, that must be well-formed.
1416     fields: Vec<AdtField<'tcx>>,
1417
1418     /// Explicit discriminant of this variant (e.g. `A = 123`),
1419     /// that must evaluate to a constant value.
1420     explicit_discr: Option<LocalDefId>,
1421 }
1422
1423 struct AdtField<'tcx> {
1424     ty: Ty<'tcx>,
1425     span: Span,
1426 }
1427
1428 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1429     // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1430     fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1431         let fields = struct_def
1432             .fields()
1433             .iter()
1434             .map(|field| {
1435                 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1436                 let field_ty = self.normalize_associated_types_in(field.ty.span, field_ty);
1437                 let field_ty = self.resolve_vars_if_possible(field_ty);
1438                 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1439                 AdtField { ty: field_ty, span: field.ty.span }
1440             })
1441             .collect();
1442         AdtVariant { fields, explicit_discr: None }
1443     }
1444
1445     fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1446         enum_def
1447             .variants
1448             .iter()
1449             .map(|variant| AdtVariant {
1450                 fields: self.non_enum_variant(&variant.data).fields,
1451                 explicit_discr: variant
1452                     .disr_expr
1453                     .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
1454             })
1455             .collect()
1456     }
1457
1458     pub(super) fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1459         match self.tcx.impl_trait_ref(impl_def_id) {
1460             Some(trait_ref) => {
1461                 // Trait impl: take implied bounds from all types that
1462                 // appear in the trait reference.
1463                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1464                 trait_ref.substs.types().collect()
1465             }
1466
1467             None => {
1468                 // Inherent impl: take implied bounds from the `self` type.
1469                 let self_ty = self.tcx.type_of(impl_def_id);
1470                 let self_ty = self.normalize_associated_types_in(span, self_ty);
1471                 vec![self_ty]
1472             }
1473         }
1474     }
1475 }
1476
1477 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) -> DiagnosticBuilder<'_> {
1478     let mut err =
1479         struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1480     err.span_label(span, "unused parameter");
1481     err
1482 }