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