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::itemlikevisit::ParItemLikeVisitor;
10 use rustc_hir::lang_items;
11 use rustc_hir::ItemKind;
12 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
13 use rustc_middle::ty::trait_def::TraitSpecializationKind;
14 use rustc_middle::ty::{
15 self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
17 use rustc_session::parse::feature_err;
18 use rustc_span::symbol::{sym, Symbol};
20 use rustc_trait_selection::opaque_types::may_define_opaque_type;
21 use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
22 use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode};
24 /// Helper type of a temporary returned by `.for_item(...)`.
25 /// This is necessary because we can't write the following bound:
28 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
30 struct CheckWfFcxBuilder<'tcx> {
31 inherited: super::InheritedBuilder<'tcx>,
34 param_env: ty::ParamEnv<'tcx>,
37 impl<'tcx> CheckWfFcxBuilder<'tcx> {
38 fn with_fcx<F>(&mut self, f: F)
40 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>, TyCtxt<'tcx>) -> Vec<Ty<'tcx>>,
44 let param_env = self.param_env;
45 self.inherited.enter(|inh| {
46 let fcx = FnCtxt::new(&inh, param_env, id);
47 if !inh.tcx.features().trivial_bounds {
48 // As predicates are cached rather than obligations, this
49 // needsto be called first so that they are checked with an
51 check_false_global_bounds(&fcx, span, id);
53 let wf_tys = f(&fcx, fcx.tcx);
54 fcx.select_all_obligations_or_error();
55 fcx.regionck_item(id, span, &wf_tys);
60 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
61 /// well-formed, meaning that they do not require any constraints not declared in the struct
62 /// definition itself. For example, this definition would be illegal:
65 /// struct Ref<'a, T> { x: &'a T }
68 /// because the type did not declare that `T:'a`.
70 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
71 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
73 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
74 let hir_id = tcx.hir().as_local_hir_id(def_id);
75 let item = tcx.hir().expect_item(hir_id);
78 "check_item_well_formed(it.hir_id={:?}, it.name={})",
80 tcx.def_path_str(def_id.to_def_id())
84 // Right now we check that every default trait implementation
85 // has an implementation of itself. Basically, a case like:
87 // impl Trait for T {}
89 // has a requirement of `T: Trait` which was required for default
90 // method implementations. Although this could be improved now that
91 // there's a better infrastructure in place for this, it's being left
92 // for a follow-up work.
94 // Since there's such a requirement, we need to check *just* positive
95 // implementations, otherwise things like:
97 // impl !Send for T {}
99 // won't be allowed unless there's an *explicit* implementation of `Send`
101 hir::ItemKind::Impl {
110 .impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
111 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
112 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
113 let sp = of_trait.as_ref().map(|t| t.path.span).unwrap_or(item.span);
115 tcx.sess.struct_span_err(sp, "impls of auto traits cannot be default");
116 err.span_labels(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), polarity) {
122 (ty::ImplPolarity::Positive, _) => {
123 check_impl(tcx, item, self_ty, 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 { .. } = defaultness {
128 let mut spans = vec![span];
129 spans.extend(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(..) => {
146 check_item_fn(tcx, item);
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(ref module) => {
155 for it in module.items.iter() {
156 if let hir::ForeignItemKind::Static(ref ty, ..) = it.kind {
157 check_item_type(tcx, it.hir_id, ty.span, true);
161 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
162 check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
164 check_variances_for_type_defn(tcx, item, ast_generics);
166 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
167 check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
169 check_variances_for_type_defn(tcx, item, ast_generics);
171 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
172 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
174 check_variances_for_type_defn(tcx, item, ast_generics);
176 hir::ItemKind::Trait(..) => {
177 check_trait(tcx, item);
179 hir::ItemKind::TraitAlias(..) => {
180 check_trait(tcx, item);
186 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
187 let hir_id = tcx.hir().as_local_hir_id(def_id);
188 let trait_item = tcx.hir().expect_trait_item(hir_id);
190 let method_sig = match trait_item.kind {
191 hir::TraitItemKind::Fn(ref sig, _) => Some(sig),
194 check_object_unsafe_self_trait_by_name(tcx, &trait_item);
195 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
198 fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool {
200 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
201 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id.to_def_id()),
208 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
209 /// When this is done, suggest using `Self` instead.
210 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
211 let (trait_name, trait_def_id) = match tcx.hir().get(tcx.hir().get_parent_item(item.hir_id)) {
212 hir::Node::Item(item) => match item.kind {
213 hir::ItemKind::Trait(..) => (item.ident, tcx.hir().local_def_id(item.hir_id)),
218 let mut trait_should_be_self = vec![];
220 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
221 if could_be_self(trait_def_id, ty) =>
223 trait_should_be_self.push(ty.span)
225 hir::TraitItemKind::Fn(sig, _) => {
226 for ty in sig.decl.inputs {
227 if could_be_self(trait_def_id, ty) {
228 trait_should_be_self.push(ty.span);
231 match sig.decl.output {
232 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
233 trait_should_be_self.push(ty.span);
240 if !trait_should_be_self.is_empty() {
241 if tcx.object_safety_violations(trait_def_id).is_empty() {
244 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
247 trait_should_be_self,
248 "associated item referring to unboxed trait object for its own trait",
250 .span_label(trait_name.span, "in this trait")
251 .multipart_suggestion(
252 "you might have meant to use `Self` to refer to the implementing type",
254 Applicability::MachineApplicable,
260 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
261 let hir_id = tcx.hir().as_local_hir_id(def_id);
262 let impl_item = tcx.hir().expect_impl_item(hir_id);
264 let method_sig = match impl_item.kind {
265 hir::ImplItemKind::Fn(ref sig, _) => Some(sig),
269 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
272 fn check_associated_item(
276 sig_if_method: Option<&hir::FnSig<'_>>,
278 debug!("check_associated_item: {:?}", item_id);
280 let code = ObligationCauseCode::MiscObligation;
281 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
282 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
284 let (mut implied_bounds, self_ty) = match item.container {
285 ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
286 ty::ImplContainer(def_id) => {
287 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
292 ty::AssocKind::Const => {
293 let ty = fcx.tcx.type_of(item.def_id);
294 let ty = fcx.normalize_associated_types_in(span, &ty);
295 fcx.register_wf_obligation(ty, span, code.clone());
297 ty::AssocKind::Fn => {
298 let sig = fcx.tcx.fn_sig(item.def_id);
299 let sig = fcx.normalize_associated_types_in(span, &sig);
300 let hir_sig = sig_if_method.expect("bad signature for method");
310 check_method_receiver(fcx, hir_sig, &item, self_ty);
312 ty::AssocKind::Type => {
313 if item.defaultness.has_value() {
314 let ty = fcx.tcx.type_of(item.def_id);
315 let ty = fcx.normalize_associated_types_in(span, &ty);
316 fcx.register_wf_obligation(ty, span, code.clone());
319 ty::AssocKind::OpaqueTy => {
320 // Do nothing: opaque types check themselves.
328 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
329 for_id(tcx, item.hir_id, item.span)
332 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
333 let def_id = tcx.hir().local_def_id(id);
335 inherited: Inherited::build(tcx, def_id),
338 param_env: tcx.param_env(def_id),
342 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
344 ItemKind::Struct(..) => Some(AdtKind::Struct),
345 ItemKind::Union(..) => Some(AdtKind::Union),
346 ItemKind::Enum(..) => Some(AdtKind::Enum),
351 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
352 fn check_type_defn<'tcx, F>(
354 item: &hir::Item<'tcx>,
356 mut lookup_fields: F,
358 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
360 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
361 let variants = lookup_fields(fcx);
362 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
363 let packed = fcx.tcx.adt_def(def_id).repr.packed();
365 for variant in &variants {
366 // For DST, or when drop needs to copy things around, all
367 // intermediate types must be sized.
368 let needs_drop_copy = || {
370 let ty = variant.fields.last().unwrap().ty;
371 let ty = fcx.tcx.erase_regions(&ty);
372 if ty.needs_infer() {
375 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
376 // Just treat unresolved type expression as if it needs drop.
379 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
383 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
384 let unsized_len = if all_sized { 0 } else { 1 };
386 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
388 let last = idx == variant.fields.len() - 1;
391 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
392 traits::ObligationCause::new(
396 adt_kind: match item_adt_kind(&item.kind) {
406 // All field types must be well-formed.
407 for field in &variant.fields {
408 fcx.register_wf_obligation(
411 ObligationCauseCode::MiscObligation,
415 // Explicit `enum` discriminant values must const-evaluate successfully.
416 if let Some(discr_def_id) = variant.explicit_discr {
418 InternalSubsts::identity_for_item(fcx.tcx, discr_def_id.to_def_id());
420 let cause = traits::ObligationCause::new(
421 fcx.tcx.def_span(discr_def_id),
423 traits::MiscObligation,
425 fcx.register_predicate(traits::Obligation::new(
428 ty::PredicateKind::ConstEvaluatable(discr_def_id.to_def_id(), discr_substs),
433 check_where_clauses(tcx, fcx, item.span, def_id.to_def_id(), None);
435 // No implied bounds in a struct definition.
440 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
441 debug!("check_trait: {:?}", item.hir_id);
443 let trait_def_id = tcx.hir().local_def_id(item.hir_id);
445 let trait_def = tcx.trait_def(trait_def_id);
446 if trait_def.is_marker
447 || matches!(trait_def.specialization_kind, TraitSpecializationKind::Marker)
449 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
452 tcx.def_span(*associated_def_id),
454 "marker traits cannot have associated items",
460 for_item(tcx, item).with_fcx(|fcx, _| {
461 check_where_clauses(tcx, fcx, item.span, trait_def_id.to_def_id(), None);
462 check_associated_type_defaults(fcx, trait_def_id.to_def_id());
468 /// Checks all associated type defaults of trait `trait_def_id`.
470 /// Assuming the defaults are used, check that all predicates (bounds on the
471 /// assoc type and where clauses on the trait) hold.
472 fn check_associated_type_defaults(fcx: &FnCtxt<'_, '_>, trait_def_id: DefId) {
474 let substs = InternalSubsts::identity_for_item(tcx, trait_def_id);
476 // For all assoc. types with defaults, build a map from
477 // `<Self as Trait<...>>::Assoc` to the default type.
479 .associated_items(trait_def_id)
480 .in_definition_order()
482 if item.kind == ty::AssocKind::Type && item.defaultness.has_value() {
483 // `<Self as Trait<...>>::Assoc`
484 let proj = ty::ProjectionTy { substs, item_def_id: item.def_id };
485 let default_ty = tcx.type_of(item.def_id);
486 debug!("assoc. type default mapping: {} -> {}", proj, default_ty);
487 Some((proj, default_ty))
492 .collect::<FxHashMap<_, _>>();
494 /// Replaces projections of associated types with their default types.
496 /// This does a "shallow substitution", meaning that defaults that refer to
497 /// other defaulted assoc. types will still refer to the projection
498 /// afterwards, not to the other default. For example:
502 /// type A: Clone = Vec<Self::B>;
507 /// This will end up replacing the bound `Self::A: Clone` with
508 /// `Vec<Self::B>: Clone`, not with `Vec<u8>: Clone`. If we did a deep
509 /// substitution and ended up with the latter, the trait would be accepted.
510 /// If an `impl` then replaced `B` with something that isn't `Clone`,
511 /// suddenly the default for `A` is no longer valid. The shallow
512 /// substitution forces the trait to add a `B: Clone` bound to be accepted,
513 /// which means that an `impl` can replace any default without breaking
516 /// Note that this isn't needed for soundness: The defaults would still be
517 /// checked in any impl that doesn't override them.
518 struct DefaultNormalizer<'tcx> {
520 map: FxHashMap<ty::ProjectionTy<'tcx>, Ty<'tcx>>,
523 impl<'tcx> ty::fold::TypeFolder<'tcx> for DefaultNormalizer<'tcx> {
524 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
528 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
530 ty::Projection(proj_ty) => {
531 if let Some(default) = self.map.get(&proj_ty) {
534 t.super_fold_with(self)
537 _ => t.super_fold_with(self),
542 // Now take all predicates defined on the trait, replace any mention of
543 // the assoc. types with their default, and prove them.
544 // We only consider predicates that directly mention the assoc. type.
545 let mut norm = DefaultNormalizer { tcx, map };
546 let predicates = fcx.tcx.predicates_of(trait_def_id);
547 for &(orig_pred, span) in predicates.predicates.iter() {
548 let pred = orig_pred.fold_with(&mut norm);
549 if pred != orig_pred {
550 // Mentions one of the defaulted assoc. types
551 debug!("default suitability check: proving predicate: {} -> {}", orig_pred, pred);
552 let pred = fcx.normalize_associated_types_in(span, &pred);
553 let cause = traits::ObligationCause::new(
556 traits::ItemObligation(trait_def_id),
558 let obligation = traits::Obligation::new(cause, fcx.param_env, pred);
560 fcx.register_predicate(obligation);
565 fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
566 for_item(tcx, item).with_fcx(|fcx, tcx| {
567 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
568 let sig = fcx.tcx.fn_sig(def_id);
569 let sig = fcx.normalize_associated_types_in(item.span, &sig);
570 let mut implied_bounds = vec![];
571 let hir_sig = match &item.kind {
572 ItemKind::Fn(sig, ..) => sig,
573 _ => bug!("expected `ItemKind::Fn`, found `{:?}`", item.kind),
588 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
589 debug!("check_item_type: {:?}", item_id);
591 for_id(tcx, item_id, ty_span).with_fcx(|fcx, tcx| {
592 let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
593 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
595 let mut forbid_unsized = true;
596 if allow_foreign_ty {
597 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
598 if let ty::Foreign(_) = tail.kind {
599 forbid_unsized = false;
603 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
607 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
608 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
612 // No implied bounds in a const, etc.
619 item: &'tcx hir::Item<'tcx>,
620 ast_self_ty: &hir::Ty<'_>,
621 ast_trait_ref: &Option<hir::TraitRef<'_>>,
623 debug!("check_impl: {:?}", item);
625 for_item(tcx, item).with_fcx(|fcx, tcx| {
626 let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
628 match *ast_trait_ref {
629 Some(ref ast_trait_ref) => {
630 // `#[rustc_reservation_impl]` impls are not real impls and
631 // therefore don't need to be WF (the trait's `Self: Trait` predicate
633 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
635 fcx.normalize_associated_types_in(ast_trait_ref.path.span, &trait_ref);
636 let obligations = traits::wf::trait_obligations(
641 ast_trait_ref.path.span,
644 for obligation in obligations {
645 fcx.register_predicate(obligation);
649 let self_ty = fcx.tcx.type_of(item_def_id);
650 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
651 fcx.register_wf_obligation(
654 ObligationCauseCode::MiscObligation,
659 check_where_clauses(tcx, fcx, item.span, item_def_id.to_def_id(), None);
661 fcx.impl_implied_bounds(item_def_id.to_def_id(), item.span)
665 /// Checks where-clauses and inline bounds that are declared on `def_id`.
666 fn check_where_clauses<'tcx, 'fcx>(
668 fcx: &FnCtxt<'fcx, 'tcx>,
671 return_ty: Option<(Ty<'tcx>, Span)>,
673 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
675 let predicates = fcx.tcx.predicates_of(def_id);
676 let generics = tcx.generics_of(def_id);
678 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
679 GenericParamDefKind::Type { has_default, .. } => {
680 has_default && def.index >= generics.parent_count as u32
685 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
686 // For example, this forbids the declaration:
688 // struct Foo<T = Vec<[u32]>> { .. }
690 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
691 for param in &generics.params {
692 if let GenericParamDefKind::Type { .. } = param.kind {
693 if is_our_default(¶m) {
694 let ty = fcx.tcx.type_of(param.def_id);
695 // Ignore dependent defaults -- that is, where the default of one type
696 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
697 // be sure if it will error or not as user might always specify the other.
698 if !ty.needs_subst() {
699 fcx.register_wf_obligation(
701 fcx.tcx.def_span(param.def_id),
702 ObligationCauseCode::MiscObligation,
709 // Check that trait predicates are WF when params are substituted by their defaults.
710 // We don't want to overly constrain the predicates that may be written but we want to
711 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
712 // Therefore we check if a predicate which contains a single type param
713 // with a concrete default is WF with that default substituted.
714 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
716 // First we build the defaulted substitution.
717 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
719 GenericParamDefKind::Lifetime => {
720 // All regions are identity.
721 fcx.tcx.mk_param_from_def(param)
724 GenericParamDefKind::Type { .. } => {
725 // If the param has a default, ...
726 if is_our_default(param) {
727 let default_ty = fcx.tcx.type_of(param.def_id);
728 // ... and it's not a dependent default, ...
729 if !default_ty.needs_subst() {
730 // ... then substitute it with the default.
731 return default_ty.into();
735 fcx.tcx.mk_param_from_def(param)
738 GenericParamDefKind::Const => {
739 // FIXME(const_generics:defaults)
740 fcx.tcx.mk_param_from_def(param)
745 // Now we build the substituted predicates.
746 let default_obligations = predicates
749 .flat_map(|&(pred, sp)| {
752 params: FxHashSet<u32>,
754 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
755 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
756 if let ty::Param(param) = t.kind {
757 self.params.insert(param.index);
759 t.super_visit_with(self)
762 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
766 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
767 if let ty::ConstKind::Param(param) = c.val {
768 self.params.insert(param.index);
770 c.super_visit_with(self)
773 let mut param_count = CountParams::default();
774 let has_region = pred.visit_with(&mut param_count);
775 let substituted_pred = pred.subst(fcx.tcx, substs);
776 // Don't check non-defaulted params, dependent defaults (including lifetimes)
777 // or preds with multiple params.
778 if substituted_pred.has_param_types_or_consts()
779 || param_count.params.len() > 1
783 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
784 // Avoid duplication of predicates that contain no parameters, for example.
787 Some((substituted_pred, sp))
791 // Convert each of those into an obligation. So if you have
792 // something like `struct Foo<T: Copy = String>`, we would
793 // take that predicate `T: Copy`, substitute to `String: Copy`
794 // (actually that happens in the previous `flat_map` call),
795 // and then try to prove it (in this case, we'll fail).
797 // Note the subtle difference from how we handle `predicates`
798 // below: there, we are not trying to prove those predicates
799 // to be *true* but merely *well-formed*.
800 let pred = fcx.normalize_associated_types_in(sp, &pred);
802 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
803 traits::Obligation::new(cause, fcx.param_env, pred)
806 let mut predicates = predicates.instantiate_identity(fcx.tcx);
808 if let Some((return_ty, span)) = return_ty {
809 let opaque_types = check_opaque_types(tcx, fcx, def_id.expect_local(), span, return_ty);
810 for _ in 0..opaque_types.len() {
811 predicates.spans.push(span);
813 predicates.predicates.extend(opaque_types);
816 let predicates = fcx.normalize_associated_types_in(span, &predicates);
818 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
819 assert_eq!(predicates.predicates.len(), predicates.spans.len());
821 predicates.predicates.iter().zip(predicates.spans.iter()).flat_map(|(p, sp)| {
822 traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, *sp)
825 for obligation in wf_obligations.chain(default_obligations) {
826 debug!("next obligation cause: {:?}", obligation.cause);
827 fcx.register_predicate(obligation);
831 fn check_fn_or_method<'fcx, 'tcx>(
833 fcx: &FnCtxt<'fcx, 'tcx>,
835 sig: ty::PolyFnSig<'tcx>,
836 hir_sig: &hir::FnSig<'_>,
838 implied_bounds: &mut Vec<Ty<'tcx>>,
840 let sig = fcx.normalize_associated_types_in(span, &sig);
841 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
843 for (input_ty, span) in sig.inputs().iter().zip(hir_sig.decl.inputs.iter().map(|t| t.span)) {
844 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
846 implied_bounds.extend(sig.inputs());
848 fcx.register_wf_obligation(
850 hir_sig.decl.output.span(),
851 ObligationCauseCode::ReturnType,
854 // FIXME(#25759) return types should not be implied bounds
855 implied_bounds.push(sig.output());
857 check_where_clauses(tcx, fcx, span, def_id, Some((sig.output(), hir_sig.decl.output.span())));
860 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
861 /// laid for "higher-order pattern unification".
862 /// This ensures that inference is tractable.
863 /// In particular, definitions of opaque types can only use other generics as arguments,
864 /// and they cannot repeat an argument. Example:
867 /// type Foo<A, B> = impl Bar<A, B>;
869 /// // Okay -- `Foo` is applied to two distinct, generic types.
870 /// fn a<T, U>() -> Foo<T, U> { .. }
872 /// // Not okay -- `Foo` is applied to `T` twice.
873 /// fn b<T>() -> Foo<T, T> { .. }
875 /// // Not okay -- `Foo` is applied to a non-generic type.
876 /// fn b<T>() -> Foo<T, u32> { .. }
879 fn check_opaque_types<'fcx, 'tcx>(
881 fcx: &FnCtxt<'fcx, 'tcx>,
882 fn_def_id: LocalDefId,
885 ) -> Vec<ty::Predicate<'tcx>> {
886 trace!("check_opaque_types(ty={:?})", ty);
887 let mut substituted_predicates = Vec::new();
888 ty.fold_with(&mut ty::fold::BottomUpFolder {
891 if let ty::Opaque(def_id, substs) = ty.kind {
892 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
893 let generics = tcx.generics_of(def_id);
894 // Only check named `impl Trait` types defined in this crate.
895 // FIXME(eddyb) is `generics.parent.is_none()` correct? It seems
896 // potentially risky wrt associated types in `impl`s.
897 if generics.parent.is_none() && def_id.is_local() {
898 let opaque_hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
899 if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
900 trace!("check_opaque_types: may define, generics={:#?}", generics);
901 let mut seen_params: FxHashMap<_, Vec<_>> = FxHashMap::default();
902 for (i, &arg) in substs.iter().enumerate() {
903 let arg_is_param = match arg.unpack() {
904 GenericArgKind::Type(ty) => matches!(ty.kind, ty::Param(_)),
906 GenericArgKind::Lifetime(region) => {
907 if let ty::ReStatic = region {
911 "non-defining opaque type use in defining scope",
914 tcx.def_span(generics.param_at(i, tcx).def_id),
915 "cannot use static lifetime; use a bound lifetime \
916 instead or remove the lifetime parameter from the \
926 GenericArgKind::Const(ct) => {
927 matches!(ct.val, ty::ConstKind::Param(_))
932 seen_params.entry(arg).or_default().push(i);
934 // Prevent `fn foo() -> Foo<u32>` from being defining.
935 let opaque_param = generics.param_at(i, tcx);
939 "non-defining opaque type use in defining scope",
942 tcx.def_span(opaque_param.def_id),
944 "used non-generic {} `{}` for generic parameter",
945 opaque_param.kind.descr(),
951 } // for (arg, param)
953 for (_, indices) in seen_params {
954 if indices.len() > 1 {
955 let descr = generics.param_at(indices[0], tcx).kind.descr();
956 let spans: Vec<_> = indices
958 .map(|i| tcx.def_span(generics.param_at(i, tcx).def_id))
963 "non-defining opaque type use in defining scope",
965 .span_note(spans, &format!("{} used multiple times", descr))
969 } // if may_define_opaque_type
971 // Now register the bounds on the parameters of the opaque type
972 // so the parameters given by the function need to fulfill them.
974 // type Foo<T: Bar> = impl Baz + 'static;
975 // fn foo<U>() -> Foo<U> { .. *}
979 // type Foo<T: Bar> = impl Baz + 'static;
980 // fn foo<U: Bar>() -> Foo<U> { .. *}
981 let predicates = tcx.predicates_of(def_id);
982 trace!("check_opaque_types: may define, predicates={:#?}", predicates,);
983 for &(pred, _) in predicates.predicates {
984 let substituted_pred = pred.subst(fcx.tcx, substs);
985 // Avoid duplication of predicates that contain no parameters, for example.
986 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
987 substituted_predicates.push(substituted_pred);
990 } // if is_named_opaque_type
997 substituted_predicates
1000 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1001 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1002 of the previous types except `Self`)";
1004 fn check_method_receiver<'fcx, 'tcx>(
1005 fcx: &FnCtxt<'fcx, 'tcx>,
1006 fn_sig: &hir::FnSig<'_>,
1007 method: &ty::AssocItem,
1010 // Check that the method has a valid receiver type, given the type `Self`.
1011 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
1013 if !method.fn_has_self_parameter {
1017 let span = fn_sig.decl.inputs[0].span;
1019 let sig = fcx.tcx.fn_sig(method.def_id);
1020 let sig = fcx.normalize_associated_types_in(span, &sig);
1021 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
1023 debug!("check_method_receiver: sig={:?}", sig);
1025 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
1026 let self_ty = fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_ty));
1028 let receiver_ty = sig.inputs()[0];
1030 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
1032 fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(receiver_ty));
1034 if fcx.tcx.features().arbitrary_self_types {
1035 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1036 // Report error; `arbitrary_self_types` was enabled.
1037 e0307(fcx, span, receiver_ty);
1040 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1041 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1042 // Report error; would have worked with `arbitrary_self_types`.
1044 &fcx.tcx.sess.parse_sess,
1045 sym::arbitrary_self_types,
1048 "`{}` cannot be used as the type of `self` without \
1049 the `arbitrary_self_types` feature",
1053 .help(HELP_FOR_SELF_TYPE)
1056 // Report error; would not have worked with `arbitrary_self_types`.
1057 e0307(fcx, span, receiver_ty);
1063 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1065 fcx.tcx.sess.diagnostic(),
1068 "invalid `self` parameter type: {:?}",
1071 .note("type of `self` must be `Self` or a type that dereferences to it")
1072 .help(HELP_FOR_SELF_TYPE)
1076 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1077 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1078 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1079 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1080 /// `Deref<Target = self_ty>`.
1082 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1083 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1084 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1085 fn receiver_is_valid<'fcx, 'tcx>(
1086 fcx: &FnCtxt<'fcx, 'tcx>,
1088 receiver_ty: Ty<'tcx>,
1090 arbitrary_self_types_enabled: bool,
1092 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1094 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1096 // `self: Self` is always valid.
1097 if can_eq_self(receiver_ty) {
1098 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1104 let mut autoderef = fcx.autoderef(span, receiver_ty);
1106 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1107 if arbitrary_self_types_enabled {
1108 autoderef = autoderef.include_raw_pointers();
1111 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1114 let receiver_trait_def_id = fcx.tcx.require_lang_item(lang_items::ReceiverTraitLangItem, None);
1116 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1118 if let Some((potential_self_ty, _)) = autoderef.next() {
1120 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1121 potential_self_ty, self_ty
1124 if can_eq_self(potential_self_ty) {
1125 autoderef.finalize(fcx);
1127 if let Some(mut err) =
1128 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1135 // Without `feature(arbitrary_self_types)`, we require that each step in the
1136 // deref chain implement `receiver`
1137 if !arbitrary_self_types_enabled
1138 && !receiver_is_implemented(
1140 receiver_trait_def_id,
1149 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1150 // If he receiver already has errors reported due to it, consider it valid to avoid
1151 // unnecessary errors (#58712).
1152 return receiver_ty.references_error();
1156 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1157 if !arbitrary_self_types_enabled
1158 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1166 fn receiver_is_implemented(
1167 fcx: &FnCtxt<'_, 'tcx>,
1168 receiver_trait_def_id: DefId,
1169 cause: ObligationCause<'tcx>,
1170 receiver_ty: Ty<'tcx>,
1172 let trait_ref = ty::TraitRef {
1173 def_id: receiver_trait_def_id,
1174 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1178 traits::Obligation::new(cause, fcx.param_env, trait_ref.without_const().to_predicate());
1180 if fcx.predicate_must_hold_modulo_regions(&obligation) {
1184 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1191 fn check_variances_for_type_defn<'tcx>(
1193 item: &hir::Item<'tcx>,
1194 hir_generics: &hir::Generics<'_>,
1196 let item_def_id = tcx.hir().local_def_id(item.hir_id);
1197 let ty = tcx.type_of(item_def_id);
1198 if tcx.has_error_field(ty) {
1202 let ty_predicates = tcx.predicates_of(item_def_id);
1203 assert_eq!(ty_predicates.parent, None);
1204 let variances = tcx.variances_of(item_def_id);
1206 let mut constrained_parameters: FxHashSet<_> = variances
1209 .filter(|&(_, &variance)| variance != ty::Bivariant)
1210 .map(|(index, _)| Parameter(index as u32))
1213 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1215 for (index, _) in variances.iter().enumerate() {
1216 if constrained_parameters.contains(&Parameter(index as u32)) {
1220 let param = &hir_generics.params[index];
1223 hir::ParamName::Error => {}
1224 _ => report_bivariance(tcx, param.span, param.name.ident().name),
1229 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) {
1230 let mut err = error_392(tcx, span, param_name);
1232 let suggested_marker_id = tcx.lang_items().phantom_data();
1233 // Help is available only in presence of lang items.
1234 let msg = if let Some(def_id) = suggested_marker_id {
1236 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1238 tcx.def_path_str(def_id),
1241 format!("consider removing `{}` or referring to it in a field", param_name)
1247 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1249 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1250 let empty_env = ty::ParamEnv::empty();
1252 let def_id = fcx.tcx.hir().local_def_id(id);
1253 let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p);
1254 // Check elaborated bounds.
1255 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1257 for obligation in implied_obligations {
1258 let pred = obligation.predicate;
1259 // Match the existing behavior.
1260 if pred.is_global() && !pred.has_late_bound_regions() {
1261 let pred = fcx.normalize_associated_types_in(span, &pred);
1262 let obligation = traits::Obligation::new(
1263 traits::ObligationCause::new(span, id, traits::TrivialBound),
1267 fcx.register_predicate(obligation);
1271 fcx.select_all_obligations_or_error();
1274 pub struct CheckTypeWellFormedVisitor<'tcx> {
1278 impl CheckTypeWellFormedVisitor<'tcx> {
1279 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1280 CheckTypeWellFormedVisitor { tcx }
1284 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1285 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1286 debug!("visit_item: {:?}", i);
1287 let def_id = self.tcx.hir().local_def_id(i.hir_id);
1288 self.tcx.ensure().check_item_well_formed(def_id);
1291 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1292 debug!("visit_trait_item: {:?}", trait_item);
1293 let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1294 self.tcx.ensure().check_trait_item_well_formed(def_id);
1297 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1298 debug!("visit_impl_item: {:?}", impl_item);
1299 let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1300 self.tcx.ensure().check_impl_item_well_formed(def_id);
1304 ///////////////////////////////////////////////////////////////////////////
1307 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1308 struct AdtVariant<'tcx> {
1309 /// Types of fields in the variant, that must be well-formed.
1310 fields: Vec<AdtField<'tcx>>,
1312 /// Explicit discriminant of this variant (e.g. `A = 123`),
1313 /// that must evaluate to a constant value.
1314 explicit_discr: Option<LocalDefId>,
1317 struct AdtField<'tcx> {
1322 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1323 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1324 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1325 let fields = struct_def
1329 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1330 let field_ty = self.normalize_associated_types_in(field.span, &field_ty);
1331 let field_ty = self.resolve_vars_if_possible(&field_ty);
1332 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1333 AdtField { ty: field_ty, span: field.span }
1336 AdtVariant { fields, explicit_discr: None }
1339 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1343 .map(|variant| AdtVariant {
1344 fields: self.non_enum_variant(&variant.data).fields,
1345 explicit_discr: variant
1347 .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
1352 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1353 match self.tcx.impl_trait_ref(impl_def_id) {
1354 Some(ref trait_ref) => {
1355 // Trait impl: take implied bounds from all types that
1356 // appear in the trait reference.
1357 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1358 trait_ref.substs.types().collect()
1362 // Inherent impl: take implied bounds from the `self` type.
1363 let self_ty = self.tcx.type_of(impl_def_id);
1364 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1371 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: Symbol) -> DiagnosticBuilder<'_> {
1373 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1374 err.span_label(span, "unused parameter");