1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
5 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
6 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
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,
20 use rustc_session::parse::feature_err;
21 use rustc_span::symbol::{sym, Ident, Symbol};
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};
27 use std::convert::TryInto;
29 use std::ops::ControlFlow;
31 /// Helper type of a temporary returned by `.for_item(...)`.
32 /// This is necessary because we can't write the following bound:
35 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
37 struct CheckWfFcxBuilder<'tcx> {
38 inherited: super::InheritedBuilder<'tcx>,
41 param_env: ty::ParamEnv<'tcx>,
44 impl<'tcx> CheckWfFcxBuilder<'tcx> {
45 fn with_fcx<F>(&mut self, f: F)
47 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>) -> Vec<Ty<'tcx>>,
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
58 check_false_global_bounds(&fcx, span, id);
61 fcx.select_all_obligations_or_error();
62 fcx.regionck_item(id, span, &wf_tys);
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:
72 /// struct Ref<'a, T> { x: &'a T }
75 /// because the type did not declare that `T:'a`.
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
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);
85 "check_item_well_formed(it.def_id={:?}, it.name={})",
87 tcx.def_path_str(def_id.to_def_id())
91 // Right now we check that every default trait implementation
92 // has an implementation of itself. Basically, a case like:
94 // impl Trait for T {}
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.
101 // Since there's such a requirement, we need to check *just* positive
102 // implementations, otherwise things like:
104 // impl !Send for T {}
106 // won't be allowed unless there's an *explicit* implementation of `Send`
108 hir::ItemKind::Impl(ref impl_) => {
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);
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");
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);
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);
134 "negative impls cannot be default impls"
139 (ty::ImplPolarity::Reservation, _) => {
140 // FIXME: what amount of WF checking do we need for reservation impls?
145 hir::ItemKind::Fn(ref sig, ..) => {
146 check_item_fn(tcx, item.hir_id(), item.ident, item.span, sig.decl);
148 hir::ItemKind::Static(ref ty, ..) => {
149 check_item_type(tcx, item.hir_id(), ty.span, false);
151 hir::ItemKind::Const(ref ty, ..) => {
152 check_item_type(tcx, item.hir_id(), ty.span, false);
154 hir::ItemKind::ForeignMod { items, .. } => {
155 for it in items.iter() {
156 let it = tcx.hir().foreign_item(it.id);
158 hir::ForeignItemKind::Fn(ref decl, ..) => {
159 check_item_fn(tcx, it.hir_id(), it.ident, it.span, decl)
161 hir::ForeignItemKind::Static(ref ty, ..) => {
162 check_item_type(tcx, it.hir_id(), ty.span, true)
164 hir::ForeignItemKind::Type => (),
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)]);
171 check_variances_for_type_defn(tcx, item, ast_generics);
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)]);
176 check_variances_for_type_defn(tcx, item, ast_generics);
178 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
179 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
181 check_variances_for_type_defn(tcx, item, ast_generics);
183 hir::ItemKind::Trait(..) => {
184 check_trait(tcx, item);
186 hir::ItemKind::TraitAlias(..) => {
187 check_trait(tcx, item);
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);
197 let method_sig = match trait_item.kind {
198 hir::TraitItemKind::Fn(ref sig, _) => Some(sig),
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);
205 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
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()),
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),
225 let mut trait_should_be_self = vec![];
227 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
228 if could_be_self(trait_def_id, ty) =>
230 trait_should_be_self.push(ty.span)
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);
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);
247 if !trait_should_be_self.is_empty() {
248 if tcx.object_safety_violations(trait_def_id).is_empty() {
251 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
254 trait_should_be_self,
255 "associated item referring to unboxed trait object for its own trait",
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",
261 Applicability::MachineApplicable,
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);
271 let method_sig = match impl_item.kind {
272 hir::ImplItemKind::Fn(ref sig, _) => Some(sig),
276 check_associated_item(tcx, impl_item.hir_id(), impl_item.span, method_sig);
279 fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
281 // We currently only check wf of const params here.
282 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => (),
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));
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"),
299 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => None,
300 ty::FnPtr(_) => Some("function pointers"),
301 ty::RawPtr(_) => Some("raw pointers"),
304 err_ty_str = format!("`{}`", ty);
305 Some(err_ty_str.as_str())
309 if let Some(unsupported_type) = err {
314 "using {} as const generic parameters is forbidden",
319 let mut err = tcx.sess.struct_span_err(
322 "{} is forbidden as the type of a const generic parameter",
326 err.note("the only supported types are integers, `bool` and `char`");
327 if tcx.sess.is_nightly_build() {
329 "more complex types are supported with `#![feature(const_generics)]`",
336 if traits::search_for_structural_match_violation(param.hir_id, param.span, tcx, ty)
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
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`).
350 "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
351 used as the type of a const parameter",
356 format!("`{}` may not derive both `PartialEq` and `Eq`", ty),
359 "it is not currently possible to use a type parameter as the type of a \
368 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
369 the type of a const parameter",
374 format!("`{}` doesn't derive both `PartialEq` and `Eq`", ty),
383 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
384 fn check_associated_item(
388 sig_if_method: Option<&hir::FnSig<'_>>,
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));
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))
402 ty::AssocKind::Const => {
403 let ty = fcx.tcx.type_of(item.def_id);
404 let ty = fcx.normalize_associated_types_in_wf(
407 WellFormedLoc::Ty(item_id.expect_owner()),
409 fcx.register_wf_obligation(ty.into(), span, code.clone());
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");
422 check_method_receiver(fcx, hir_sig, &item, self_ty);
424 ty::AssocKind::Type => {
425 if let ty::AssocItemContainer::TraitContainer(_) = item.container {
426 check_associated_type_bounds(fcx, item, span)
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(
433 WellFormedLoc::Ty(item_id.expect_owner()),
435 fcx.register_wf_obligation(ty.into(), span, code.clone());
444 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
445 for_id(tcx, item.hir_id(), item.span)
448 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
449 let def_id = tcx.hir().local_def_id(id);
451 inherited: Inherited::build(tcx, def_id),
454 param_env: tcx.param_env(def_id),
458 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
460 ItemKind::Struct(..) => Some(AdtKind::Struct),
461 ItemKind::Union(..) => Some(AdtKind::Union),
462 ItemKind::Enum(..) => Some(AdtKind::Enum),
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>(
470 item: &hir::Item<'tcx>,
472 mut lookup_fields: F,
474 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
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();
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 = || {
485 let ty = variant.fields.last().unwrap().ty;
486 let ty = tcx.erase_regions(ty);
487 if ty.needs_infer() {
489 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
490 // Just treat unresolved type expression as if it needs drop.
493 ty.needs_drop(tcx, tcx.param_env(item.def_id))
497 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
498 let unsized_len = if all_sized { 0 } else { 1 };
500 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
502 let last = idx == variant.fields.len() - 1;
505 tcx.require_lang_item(LangItem::Sized, None),
506 traits::ObligationCause::new(
510 adt_kind: match item_adt_kind(&item.kind) {
521 // All field types must be well-formed.
522 for field in &variant.fields {
523 fcx.register_wf_obligation(
526 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(field.def_id))),
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());
534 let cause = traits::ObligationCause::new(
535 tcx.def_span(discr_def_id),
537 traits::MiscObligation,
539 fcx.register_predicate(traits::Obligation::new(
542 ty::PredicateKind::ConstEvaluatable(
543 ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
551 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
553 // No implied bounds in a struct definition.
558 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
559 debug!("check_trait: {:?}", item.def_id);
561 let trait_def = tcx.trait_def(item.def_id);
562 if trait_def.is_marker
563 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
565 for associated_def_id in &*tcx.associated_item_def_ids(item.def_id) {
568 tcx.def_span(*associated_def_id),
570 "marker traits cannot have associated items",
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);
584 /// Checks all associated type defaults of trait `trait_def_id`.
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) {
591 let bounds = tcx.explicit_item_bounds(item.def_id);
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(
605 for obligation in wf_obligations {
606 debug!("next obligation cause: {:?}", obligation.cause);
607 fcx.register_predicate(obligation);
616 decl: &hir::FnDecl<'_>,
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);
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);
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(
635 WellFormedLoc::Ty(item_id.expect_owner()),
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;
646 fcx.register_wf_obligation(
649 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id.expect_owner()))),
654 tcx.require_lang_item(LangItem::Sized, None),
655 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
659 // No implied bounds in a const, etc.
664 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
667 item: &'tcx hir::Item<'tcx>,
668 ast_self_ty: &hir::Ty<'_>,
669 ast_trait_ref: &Option<hir::TraitRef<'_>>,
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
677 let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
679 fcx.normalize_associated_types_in(ast_trait_ref.path.span, trait_ref);
680 let obligations = traits::wf::trait_obligations(
685 ast_trait_ref.path.span,
688 debug!(?obligations);
689 for obligation in obligations {
690 fcx.register_predicate(obligation);
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(
699 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(
700 item.hir_id().expect_owner(),
706 check_where_clauses(fcx, item.span, item.def_id.to_def_id(), None);
708 fcx.impl_implied_bounds(item.def_id.to_def_id(), item.span)
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>,
717 return_ty: Option<(Ty<'tcx>, Span)>,
719 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
722 let predicates = tcx.predicates_of(def_id);
723 let generics = tcx.generics_of(def_id);
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
730 GenericParamDefKind::Lifetime => unreachable!(),
733 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
734 // For example, this forbids the declaration:
736 // struct Foo<T = Vec<[u32]>> { .. }
738 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
739 for param in &generics.params {
741 GenericParamDefKind::Type { .. } => {
742 if is_our_default(¶m) {
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(
750 tcx.def_span(param.def_id),
751 ObligationCauseCode::MiscObligation,
756 GenericParamDefKind::Const { .. } => {
757 if is_our_default(¶m) {
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(
766 tcx.def_span(param.def_id),
767 ObligationCauseCode::WellFormed(None),
772 // Doesn't have defaults.
773 GenericParamDefKind::Lifetime => {}
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`.
784 // First we build the defaulted substitution.
785 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
787 GenericParamDefKind::Lifetime => {
788 // All regions are identity.
789 tcx.mk_param_from_def(param)
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();
803 tcx.mk_param_from_def(param)
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();
816 tcx.mk_param_from_def(param)
821 // Now we build the substituted predicates.
822 let default_obligations = predicates
825 .flat_map(|&(pred, sp)| {
828 params: FxHashSet<u32>,
830 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
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);
837 t.super_visit_with(self)
840 fn visit_region(&mut self, _: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
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);
848 c.super_visit_with(self)
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
861 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
862 // Avoid duplication of predicates that contain no parameters, for example.
865 Some((substituted_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).
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);
880 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
881 traits::Obligation::new(cause, fcx.param_env, pred)
884 let predicates = predicates.instantiate_identity(tcx);
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);
891 check_opaque_types(fcx, def_id.expect_local(), span, return_ty);
894 let predicates = fcx.normalize_associated_types_in(span, predicates);
896 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
897 assert_eq!(predicates.predicates.len(), predicates.spans.len());
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)
903 for obligation in wf_obligations.chain(default_obligations) {
904 debug!("next obligation cause: {:?}", obligation.cause);
905 fcx.register_predicate(obligation);
909 fn check_fn_or_method<'fcx, 'tcx>(
910 fcx: &FnCtxt<'fcx, 'tcx>,
912 sig: ty::PolyFnSig<'tcx>,
913 hir_decl: &hir::FnDecl<'_>,
915 implied_bounds: &mut Vec<Ty<'tcx>>,
917 let sig = fcx.tcx.liberate_late_bound_regions(def_id, sig);
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;
926 fcx.tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
927 fcx.normalize_associated_types_in_wf(
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(),
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 {
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),
949 for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
950 fcx.register_wf_obligation(
953 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
954 function: def_id.expect_local(),
955 param_idx: i.try_into().unwrap(),
960 implied_bounds.extend(sig.inputs());
962 fcx.register_wf_obligation(
964 hir_decl.output.span(),
965 ObligationCauseCode::ReturnType,
968 // FIXME(#25759) return types should not be implied bounds
969 implied_bounds.push(sig.output());
971 check_where_clauses(fcx, span, def_id, Some((sig.output(), hir_decl.output.span())));
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:
981 /// type Foo<A, B> = impl Bar<A, B>;
983 /// // Okay -- `Foo` is applied to two distinct, generic types.
984 /// fn a<T, U>() -> Foo<T, U> { .. }
986 /// // Not okay -- `Foo` is applied to `T` twice.
987 /// fn b<T>() -> Foo<T, T> { .. }
989 /// // Not okay -- `Foo` is applied to a non-generic type.
990 /// fn b<T>() -> Foo<T, u32> { .. }
993 fn check_opaque_types<'fcx, 'tcx>(
994 fcx: &FnCtxt<'fcx, 'tcx>,
995 fn_def_id: LocalDefId,
999 trace!("check_opaque_types(fn_def_id={:?}, ty={:?})", fn_def_id, ty);
1002 ty.fold_with(&mut ty::fold::BottomUpFolder {
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);
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)
1012 // Opaque types from other crates won't have defining uses in this crate.
1015 if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) =
1016 tcx.hir().expect_item(opaque_hir_id).kind
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
1022 // fn foo<P0..Pn>() -> impl Trait
1026 // type Foo<P0...Pn>
1027 // fn foo<P0..Pn>() -> Foo<P0...Pn>.
1029 // For lifetime parameters we convert
1031 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
1035 // type foo::<'p0..'pn>::Foo<'q0..'qm>
1036 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
1038 // which would error here on all of the `'static` args.
1041 if !may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
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(_)),
1050 GenericArgKind::Lifetime(region) => {
1051 if let ty::ReStatic = region {
1055 "non-defining opaque type use in defining scope",
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 \
1070 GenericArgKind::Const(ct) => matches!(ct.val, ty::ConstKind::Param(_)),
1074 seen_params.entry(arg).or_default().push(i);
1076 // Prevent `fn foo() -> Foo<u32>` from being defining.
1077 let opaque_param = generics.param_at(i, tcx);
1079 .struct_span_err(span, "non-defining opaque type use in defining scope")
1081 tcx.def_span(opaque_param.def_id),
1083 "used non-generic {} `{}` for generic parameter",
1084 opaque_param.kind.descr(),
1090 } // for (arg, param)
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
1097 .map(|i| tcx.def_span(generics.param_at(i, tcx).def_id))
1100 .struct_span_err(span, "non-defining opaque type use in defining scope")
1101 .span_note(spans, &format!("{} used multiple times", descr))
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`)";
1117 fn check_method_receiver<'fcx, 'tcx>(
1118 fcx: &FnCtxt<'fcx, 'tcx>,
1119 fn_sig: &hir::FnSig<'_>,
1120 method: &ty::AssocItem,
1123 // Check that the method has a valid receiver type, given the type `Self`.
1124 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
1126 if !method.fn_has_self_parameter {
1130 let span = fn_sig.decl.inputs[0].span;
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);
1136 debug!("check_method_receiver: sig={:?}", sig);
1138 let self_ty = fcx.normalize_associated_types_in(span, self_ty);
1140 let receiver_ty = sig.inputs()[0];
1141 let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
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);
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`.
1153 &fcx.tcx.sess.parse_sess,
1154 sym::arbitrary_self_types,
1157 "`{}` cannot be used as the type of `self` without \
1158 the `arbitrary_self_types` feature",
1162 .help(HELP_FOR_SELF_TYPE)
1165 // Report error; would not have worked with `arbitrary_self_types`.
1166 e0307(fcx, span, receiver_ty);
1172 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1174 fcx.tcx.sess.diagnostic(),
1177 "invalid `self` parameter type: {}",
1180 .note("type of `self` must be `Self` or a type that dereferences to it")
1181 .help(HELP_FOR_SELF_TYPE)
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>`.
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>,
1197 receiver_ty: Ty<'tcx>,
1199 arbitrary_self_types_enabled: bool,
1201 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1203 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
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) {
1213 let mut autoderef = fcx.autoderef(span, receiver_ty);
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();
1220 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1223 let receiver_trait_def_id = fcx.tcx.require_lang_item(LangItem::Receiver, None);
1225 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1227 if let Some((potential_self_ty, _)) = autoderef.next() {
1229 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1230 potential_self_ty, self_ty
1233 if can_eq_self(potential_self_ty) {
1234 fcx.register_predicates(autoderef.into_obligations());
1236 if let Some(mut err) =
1237 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
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(
1249 receiver_trait_def_id,
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();
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)
1275 fn receiver_is_implemented(
1276 fcx: &FnCtxt<'_, 'tcx>,
1277 receiver_trait_def_id: DefId,
1278 cause: ObligationCause<'tcx>,
1279 receiver_ty: Ty<'tcx>,
1281 let trait_ref = ty::TraitRef {
1282 def_id: receiver_trait_def_id,
1283 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1286 let obligation = traits::Obligation::new(
1289 trait_ref.without_const().to_predicate(fcx.tcx),
1292 if fcx.predicate_must_hold_modulo_regions(&obligation) {
1296 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1303 fn check_variances_for_type_defn<'tcx>(
1305 item: &hir::Item<'tcx>,
1306 hir_generics: &hir::Generics<'_>,
1308 let ty = tcx.type_of(item.def_id);
1309 if tcx.has_error_field(ty) {
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);
1317 let mut constrained_parameters: FxHashSet<_> = variances
1320 .filter(|&(_, &variance)| variance != ty::Bivariant)
1321 .map(|(index, _)| Parameter(index as u32))
1324 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1326 for (index, _) in variances.iter().enumerate() {
1327 if constrained_parameters.contains(&Parameter(index as u32)) {
1331 let param = &hir_generics.params[index];
1334 hir::ParamName::Error => {}
1335 _ => report_bivariance(tcx, param),
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);
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 {
1349 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1351 tcx.def_path_str(def_id),
1354 format!("consider removing `{}` or referring to it in a field", param_name)
1358 if matches!(param.kind, rustc_hir::GenericParamKind::Type { .. }) {
1360 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1367 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1369 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1370 let empty_env = ty::ParamEnv::empty();
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);
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),
1387 fcx.register_predicate(obligation);
1391 fcx.select_all_obligations_or_error();
1394 #[derive(Clone, Copy)]
1395 pub struct CheckTypeWellFormedVisitor<'tcx> {
1399 impl CheckTypeWellFormedVisitor<'tcx> {
1400 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1401 CheckTypeWellFormedVisitor { tcx }
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);
1410 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1411 Visitor::visit_trait_item(&mut self.clone(), trait_item);
1414 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1415 Visitor::visit_impl_item(&mut self.clone(), impl_item);
1418 fn visit_foreign_item(&self, foreign_item: &'tcx hir::ForeignItem<'tcx>) {
1419 Visitor::visit_foreign_item(&mut self.clone(), foreign_item)
1423 impl Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1424 type Map = hir_map::Map<'tcx>;
1426 fn nested_visit_map(&mut self) -> hir_visit::NestedVisitorMap<Self::Map> {
1427 hir_visit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
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);
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);
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);
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);
1454 ///////////////////////////////////////////////////////////////////////////
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>>,
1462 /// Explicit discriminant of this variant (e.g. `A = 123`),
1463 /// that must evaluate to a constant value.
1464 explicit_discr: Option<LocalDefId>,
1467 struct AdtField<'tcx> {
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
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 }
1488 AdtVariant { fields, explicit_discr: None }
1491 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1495 .map(|variant| AdtVariant {
1496 fields: self.non_enum_variant(&variant.data).fields,
1497 explicit_discr: variant
1499 .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
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()
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);
1523 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) -> DiagnosticBuilder<'_> {
1525 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1526 err.span_label(span, "unused parameter");