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