1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
4 use rustc::middle::lang_items;
5 use rustc::session::parse::feature_err;
6 use rustc::ty::subst::{InternalSubsts, Subst};
8 self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::ItemKind;
14 use rustc_infer::infer::opaque_types::may_define_opaque_type;
15 use rustc_infer::traits::{self, ObligationCause, ObligationCauseCode};
16 use rustc_span::symbol::sym;
21 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
23 /// Helper type of a temporary returned by `.for_item(...)`.
24 /// This is necessary because we can't write the following bound:
27 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
29 struct CheckWfFcxBuilder<'tcx> {
30 inherited: super::InheritedBuilder<'tcx>,
33 param_env: ty::ParamEnv<'tcx>,
36 impl<'tcx> CheckWfFcxBuilder<'tcx> {
37 fn with_fcx<F>(&mut self, f: F)
39 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>, TyCtxt<'tcx>) -> Vec<Ty<'tcx>>,
43 let param_env = self.param_env;
44 self.inherited.enter(|inh| {
45 let fcx = FnCtxt::new(&inh, param_env, id);
46 if !inh.tcx.features().trivial_bounds {
47 // As predicates are cached rather than obligations, this
48 // needsto be called first so that they are checked with an
50 check_false_global_bounds(&fcx, span, id);
52 let wf_tys = f(&fcx, fcx.tcx);
53 fcx.select_all_obligations_or_error();
54 fcx.regionck_item(id, span, &wf_tys);
59 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
60 /// well-formed, meaning that they do not require any constraints not declared in the struct
61 /// definition itself. For example, this definition would be illegal:
64 /// struct Ref<'a, T> { x: &'a T }
67 /// because the type did not declare that `T:'a`.
69 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
70 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
72 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
73 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
74 let item = tcx.hir().expect_item(hir_id);
77 "check_item_well_formed(it.hir_id={:?}, it.name={})",
79 tcx.def_path_str(def_id)
83 // Right now we check that every default trait implementation
84 // has an implementation of itself. Basically, a case like:
86 // impl Trait for T {}
88 // has a requirement of `T: Trait` which was required for default
89 // method implementations. Although this could be improved now that
90 // there's a better infrastructure in place for this, it's being left
91 // for a follow-up work.
93 // Since there's such a requirement, we need to check *just* positive
94 // implementations, otherwise things like:
96 // impl !Send for T {}
98 // won't be allowed unless there's an *explicit* implementation of `Send`
100 hir::ItemKind::Impl { defaultness, ref of_trait, ref self_ty, .. } => {
102 .impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
103 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
104 let polarity = tcx.impl_polarity(def_id);
105 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
106 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
109 ty::ImplPolarity::Positive => {
110 check_impl(tcx, item, self_ty, of_trait);
112 ty::ImplPolarity::Negative => {
113 // FIXME(#27579): what amount of WF checking do we need for neg impls?
114 if of_trait.is_some() && !is_auto {
119 "negative impls are only allowed for \
120 auto traits (e.g., `Send` and `Sync`)"
125 ty::ImplPolarity::Reservation => {
126 // FIXME: what amount of WF checking do we need for reservation impls?
130 hir::ItemKind::Fn(..) => {
131 check_item_fn(tcx, item);
133 hir::ItemKind::Static(ref ty, ..) => {
134 check_item_type(tcx, item.hir_id, ty.span, false);
136 hir::ItemKind::Const(ref ty, ..) => {
137 check_item_type(tcx, item.hir_id, ty.span, false);
139 hir::ItemKind::ForeignMod(ref module) => {
140 for it in module.items.iter() {
141 if let hir::ForeignItemKind::Static(ref ty, ..) = it.kind {
142 check_item_type(tcx, it.hir_id, ty.span, true);
146 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
147 check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
149 check_variances_for_type_defn(tcx, item, ast_generics);
151 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
152 check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
154 check_variances_for_type_defn(tcx, item, ast_generics);
156 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
157 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
159 check_variances_for_type_defn(tcx, item, ast_generics);
161 hir::ItemKind::Trait(..) => {
162 check_trait(tcx, item);
164 hir::ItemKind::TraitAlias(..) => {
165 check_trait(tcx, item);
171 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: DefId) {
172 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
173 let trait_item = tcx.hir().expect_trait_item(hir_id);
175 let method_sig = match trait_item.kind {
176 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
179 check_object_unsafe_self_trait_by_name(tcx, &trait_item);
180 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
183 fn could_be_self(trait_def_id: DefId, ty: &hir::Ty<'_>) -> bool {
185 hir::TyKind::TraitObject([trait_ref], ..) => match trait_ref.trait_ref.path.segments {
186 [s] => s.res.and_then(|r| r.opt_def_id()) == Some(trait_def_id),
193 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
194 /// When this is done, suggest using `Self` instead.
195 fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) {
196 let (trait_name, trait_def_id) = match tcx.hir().get(tcx.hir().get_parent_item(item.hir_id)) {
197 hir::Node::Item(item) => match item.kind {
198 hir::ItemKind::Trait(..) => (item.ident, tcx.hir().local_def_id(item.hir_id)),
203 let mut trait_should_be_self = vec![];
205 hir::TraitItemKind::Const(ty, _) | hir::TraitItemKind::Type(_, Some(ty))
206 if could_be_self(trait_def_id, ty) =>
208 trait_should_be_self.push(ty.span)
210 hir::TraitItemKind::Method(sig, _) => {
211 for ty in sig.decl.inputs {
212 if could_be_self(trait_def_id, ty) {
213 trait_should_be_self.push(ty.span);
216 match sig.decl.output {
217 hir::FnRetTy::Return(ty) if could_be_self(trait_def_id, ty) => {
218 trait_should_be_self.push(ty.span);
225 if !trait_should_be_self.is_empty() {
226 if rustc_infer::traits::object_safety_violations(tcx, trait_def_id).is_empty() {
229 let sugg = trait_should_be_self.iter().map(|span| (*span, "Self".to_string())).collect();
232 trait_should_be_self,
233 "associated item referring to unboxed trait object for its own trait",
235 .span_label(trait_name.span, "in this trait")
236 .multipart_suggestion(
237 "you might have meant to use `Self` to refer to the implementing type",
239 Applicability::MachineApplicable,
245 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) {
246 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
247 let impl_item = tcx.hir().expect_impl_item(hir_id);
249 let method_sig = match impl_item.kind {
250 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
254 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
257 fn check_associated_item(
261 sig_if_method: Option<&hir::FnSig<'_>>,
263 debug!("check_associated_item: {:?}", item_id);
265 let code = ObligationCauseCode::MiscObligation;
266 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
267 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
269 let (mut implied_bounds, self_ty) = match item.container {
270 ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
271 ty::ImplContainer(def_id) => {
272 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
277 ty::AssocKind::Const => {
278 let ty = fcx.tcx.type_of(item.def_id);
279 let ty = fcx.normalize_associated_types_in(span, &ty);
280 fcx.register_wf_obligation(ty, span, code.clone());
282 ty::AssocKind::Method => {
283 let sig = fcx.tcx.fn_sig(item.def_id);
284 let sig = fcx.normalize_associated_types_in(span, &sig);
285 let hir_sig = sig_if_method.expect("bad signature for method");
295 check_method_receiver(fcx, hir_sig, &item, self_ty);
297 ty::AssocKind::Type => {
298 if item.defaultness.has_value() {
299 let ty = fcx.tcx.type_of(item.def_id);
300 let ty = fcx.normalize_associated_types_in(span, &ty);
301 fcx.register_wf_obligation(ty, span, code.clone());
304 ty::AssocKind::OpaqueTy => {
305 // Do nothing: opaque types check themselves.
313 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
314 for_id(tcx, item.hir_id, item.span)
317 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
318 let def_id = tcx.hir().local_def_id(id);
320 inherited: Inherited::build(tcx, def_id),
323 param_env: tcx.param_env(def_id),
327 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
329 ItemKind::Struct(..) => Some(AdtKind::Struct),
330 ItemKind::Union(..) => Some(AdtKind::Union),
331 ItemKind::Enum(..) => Some(AdtKind::Enum),
336 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
337 fn check_type_defn<'tcx, F>(
339 item: &hir::Item<'tcx>,
341 mut lookup_fields: F,
343 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
345 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
346 let variants = lookup_fields(fcx);
347 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
348 let packed = fcx.tcx.adt_def(def_id).repr.packed();
350 for variant in &variants {
351 // For DST, or when drop needs to copy things around, all
352 // intermediate types must be sized.
353 let needs_drop_copy = || {
355 let ty = variant.fields.last().unwrap().ty;
356 let ty = fcx.tcx.erase_regions(&ty);
357 if ty.has_local_value() {
360 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
361 // Just treat unresolved type expression as if it needs drop.
364 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
368 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
369 let unsized_len = if all_sized { 0 } else { 1 };
371 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
373 let last = idx == variant.fields.len() - 1;
376 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
377 traits::ObligationCause::new(
381 adt_kind: match item_adt_kind(&item.kind) {
391 // All field types must be well-formed.
392 for field in &variant.fields {
393 fcx.register_wf_obligation(
396 ObligationCauseCode::MiscObligation,
401 check_where_clauses(tcx, fcx, item.span, def_id, None);
403 // No implied bounds in a struct definition.
408 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
409 debug!("check_trait: {:?}", item.hir_id);
411 let trait_def_id = tcx.hir().local_def_id(item.hir_id);
413 let trait_def = tcx.trait_def(trait_def_id);
414 if trait_def.is_marker {
415 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
418 tcx.def_span(*associated_def_id),
420 "marker traits cannot have associated items",
426 for_item(tcx, item).with_fcx(|fcx, _| {
427 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
428 check_associated_type_defaults(fcx, trait_def_id);
434 /// Checks all associated type defaults of trait `trait_def_id`.
436 /// Assuming the defaults are used, check that all predicates (bounds on the
437 /// assoc type and where clauses on the trait) hold.
438 fn check_associated_type_defaults(
439 fcx: &FnCtxt<'_, '_>,
443 let substs = InternalSubsts::identity_for_item(tcx, trait_def_id);
445 // For all assoc. types with defaults, build a map from
446 // `<Self as Trait<...>>::Assoc` to the default type.
447 let map = tcx.associated_items(trait_def_id)
449 if item.kind == ty::AssocKind::Type && item.defaultness.has_value() {
450 // `<Self as Trait<...>>::Assoc`
451 let proj = ty::ProjectionTy {
453 item_def_id: item.def_id,
455 let default_ty = tcx.type_of(item.def_id);
456 debug!("assoc. type default mapping: {} -> {}", proj, default_ty);
457 Some((proj, default_ty))
462 .collect::<FxHashMap<_, _>>();
464 /// Replaces projections of associated types with their default types.
466 /// This does a "shallow substitution", meaning that defaults that refer to
467 /// other defaulted assoc. types will still refer to the projection
468 /// afterwards, not to the other default. For example:
472 /// type A: Clone = Vec<Self::B>;
477 /// This will end up replacing the bound `Self::A: Clone` with
478 /// `Vec<Self::B>: Clone`, not with `Vec<u8>: Clone`. If we did a deep
479 /// substitution and ended up with the latter, the trait would be accepted.
480 /// If an `impl` then replaced `B` with something that isn't `Clone`,
481 /// suddenly the default for `A` is no longer valid. The shallow
482 /// substitution forces the trait to add a `B: Clone` bound to be accepted,
483 /// which means that an `impl` can replace any default without breaking
485 struct DefaultNormalizer<'tcx> {
487 map: FxHashMap<ty::ProjectionTy<'tcx>, Ty<'tcx>>,
490 impl<'tcx> ty::fold::TypeFolder<'tcx> for DefaultNormalizer<'tcx> {
491 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
495 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
497 ty::Projection(proj_ty) => {
498 if let Some(default) = self.map.get(&proj_ty) {
501 t.super_fold_with(self)
504 _ => t.super_fold_with(self),
509 // Now take all predicates defined on the trait, replace any mention of
510 // the assoc. types with their default, and prove them.
511 // We only consider predicates that directly mention the assoc. type.
512 let mut norm = DefaultNormalizer { tcx, map };
513 let predicates = fcx.tcx.predicates_of(trait_def_id);
514 for &(orig_pred, span) in predicates.predicates.iter() {
515 let pred = orig_pred.fold_with(&mut norm);
516 if pred != orig_pred {
517 // Mentions one of the defaulted assoc. types
518 debug!("default suitability check: proving predicate: {} -> {}", orig_pred, pred);
519 let pred = fcx.normalize_associated_types_in(span, &pred);
520 let cause = traits::ObligationCause::new(
523 traits::ItemObligation(trait_def_id),
525 let obligation = traits::Obligation::new(cause, fcx.param_env, pred);
527 fcx.register_predicate(obligation);
532 fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
533 for_item(tcx, item).with_fcx(|fcx, tcx| {
534 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
535 let sig = fcx.tcx.fn_sig(def_id);
536 let sig = fcx.normalize_associated_types_in(item.span, &sig);
537 let mut implied_bounds = vec![];
538 let hir_sig = match &item.kind {
539 ItemKind::Fn(sig, ..) => sig,
540 _ => bug!("expected `ItemKind::Fn`, found `{:?}`", item.kind),
542 check_fn_or_method(tcx, fcx, item.ident.span, sig, hir_sig, def_id, &mut implied_bounds);
547 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
548 debug!("check_item_type: {:?}", item_id);
550 for_id(tcx, item_id, ty_span).with_fcx(|fcx, tcx| {
551 let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
552 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
554 let mut forbid_unsized = true;
555 if allow_foreign_ty {
556 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
557 if let ty::Foreign(_) = tail.kind {
558 forbid_unsized = false;
562 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
566 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
567 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
571 // No implied bounds in a const, etc.
578 item: &'tcx hir::Item<'tcx>,
579 ast_self_ty: &hir::Ty<'_>,
580 ast_trait_ref: &Option<hir::TraitRef<'_>>,
582 debug!("check_impl: {:?}", item);
584 for_item(tcx, item).with_fcx(|fcx, tcx| {
585 let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
587 match *ast_trait_ref {
588 Some(ref ast_trait_ref) => {
589 // `#[rustc_reservation_impl]` impls are not real impls and
590 // therefore don't need to be WF (the trait's `Self: Trait` predicate
592 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
594 fcx.normalize_associated_types_in(ast_trait_ref.path.span, &trait_ref);
595 let obligations = traits::wf::trait_obligations(
600 ast_trait_ref.path.span,
603 for obligation in obligations {
604 fcx.register_predicate(obligation);
608 let self_ty = fcx.tcx.type_of(item_def_id);
609 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
610 fcx.register_wf_obligation(
613 ObligationCauseCode::MiscObligation,
618 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
620 fcx.impl_implied_bounds(item_def_id, item.span)
624 /// Checks where-clauses and inline bounds that are declared on `def_id`.
625 fn check_where_clauses<'tcx, 'fcx>(
627 fcx: &FnCtxt<'fcx, 'tcx>,
630 return_ty: Option<(Ty<'tcx>, Span)>,
632 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
634 let predicates = fcx.tcx.predicates_of(def_id);
635 let generics = tcx.generics_of(def_id);
637 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
638 GenericParamDefKind::Type { has_default, .. } => {
639 has_default && def.index >= generics.parent_count as u32
644 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
645 // For example, this forbids the declaration:
647 // struct Foo<T = Vec<[u32]>> { .. }
649 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
650 for param in &generics.params {
651 if let GenericParamDefKind::Type { .. } = param.kind {
652 if is_our_default(¶m) {
653 let ty = fcx.tcx.type_of(param.def_id);
654 // Ignore dependent defaults -- that is, where the default of one type
655 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
656 // be sure if it will error or not as user might always specify the other.
657 if !ty.needs_subst() {
658 fcx.register_wf_obligation(
660 fcx.tcx.def_span(param.def_id),
661 ObligationCauseCode::MiscObligation,
668 // Check that trait predicates are WF when params are substituted by their defaults.
669 // We don't want to overly constrain the predicates that may be written but we want to
670 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
671 // Therefore we check if a predicate which contains a single type param
672 // with a concrete default is WF with that default substituted.
673 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
675 // First we build the defaulted substitution.
676 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
678 GenericParamDefKind::Lifetime => {
679 // All regions are identity.
680 fcx.tcx.mk_param_from_def(param)
683 GenericParamDefKind::Type { .. } => {
684 // If the param has a default, ...
685 if is_our_default(param) {
686 let default_ty = fcx.tcx.type_of(param.def_id);
687 // ... and it's not a dependent default, ...
688 if !default_ty.needs_subst() {
689 // ... then substitute it with the default.
690 return default_ty.into();
693 // Mark unwanted params as error.
694 fcx.tcx.types.err.into()
697 GenericParamDefKind::Const => {
698 // FIXME(const_generics:defaults)
699 fcx.tcx.consts.err.into()
704 // Now we build the substituted predicates.
705 let default_obligations = predicates
708 .flat_map(|&(pred, sp)| {
711 params: FxHashSet<u32>,
713 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
714 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
715 if let ty::Param(param) = t.kind {
716 self.params.insert(param.index);
718 t.super_visit_with(self)
721 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
725 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
726 if let ty::ConstKind::Param(param) = c.val {
727 self.params.insert(param.index);
729 c.super_visit_with(self)
732 let mut param_count = CountParams::default();
733 let has_region = pred.visit_with(&mut param_count);
734 let substituted_pred = pred.subst(fcx.tcx, substs);
735 // Don't check non-defaulted params, dependent defaults (including lifetimes)
736 // or preds with multiple params.
737 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
739 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
740 // Avoid duplication of predicates that contain no parameters, for example.
743 Some((substituted_pred, sp))
747 // Convert each of those into an obligation. So if you have
748 // something like `struct Foo<T: Copy = String>`, we would
749 // take that predicate `T: Copy`, substitute to `String: Copy`
750 // (actually that happens in the previous `flat_map` call),
751 // and then try to prove it (in this case, we'll fail).
753 // Note the subtle difference from how we handle `predicates`
754 // below: there, we are not trying to prove those predicates
755 // to be *true* but merely *well-formed*.
756 let pred = fcx.normalize_associated_types_in(sp, &pred);
758 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
759 traits::Obligation::new(cause, fcx.param_env, pred)
762 let mut predicates = predicates.instantiate_identity(fcx.tcx);
764 if let Some((return_ty, span)) = return_ty {
765 let opaque_types = check_opaque_types(tcx, fcx, def_id, span, return_ty);
766 for _ in 0..opaque_types.len() {
767 predicates.spans.push(span);
769 predicates.predicates.extend(opaque_types);
772 let predicates = fcx.normalize_associated_types_in(span, &predicates);
774 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
775 assert_eq!(predicates.predicates.len(), predicates.spans.len());
777 predicates.predicates.iter().zip(predicates.spans.iter()).flat_map(|(p, sp)| {
778 traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, *sp)
781 for obligation in wf_obligations.chain(default_obligations) {
782 debug!("next obligation cause: {:?}", obligation.cause);
783 fcx.register_predicate(obligation);
787 fn check_fn_or_method<'fcx, 'tcx>(
789 fcx: &FnCtxt<'fcx, 'tcx>,
791 sig: ty::PolyFnSig<'tcx>,
792 hir_sig: &hir::FnSig<'_>,
794 implied_bounds: &mut Vec<Ty<'tcx>>,
796 let sig = fcx.normalize_associated_types_in(span, &sig);
797 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
799 for (input_ty, span) in sig.inputs().iter().zip(hir_sig.decl.inputs.iter().map(|t| t.span)) {
800 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
802 implied_bounds.extend(sig.inputs());
804 fcx.register_wf_obligation(
806 hir_sig.decl.output.span(),
807 ObligationCauseCode::ReturnType,
810 // FIXME(#25759) return types should not be implied bounds
811 implied_bounds.push(sig.output());
813 check_where_clauses(tcx, fcx, span, def_id, Some((sig.output(), hir_sig.decl.output.span())));
816 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
817 /// laid for "higher-order pattern unification".
818 /// This ensures that inference is tractable.
819 /// In particular, definitions of opaque types can only use other generics as arguments,
820 /// and they cannot repeat an argument. Example:
823 /// type Foo<A, B> = impl Bar<A, B>;
825 /// // Okay -- `Foo` is applied to two distinct, generic types.
826 /// fn a<T, U>() -> Foo<T, U> { .. }
828 /// // Not okay -- `Foo` is applied to `T` twice.
829 /// fn b<T>() -> Foo<T, T> { .. }
831 /// // Not okay -- `Foo` is applied to a non-generic type.
832 /// fn b<T>() -> Foo<T, u32> { .. }
835 fn check_opaque_types<'fcx, 'tcx>(
837 fcx: &FnCtxt<'fcx, 'tcx>,
841 ) -> Vec<ty::Predicate<'tcx>> {
842 trace!("check_opaque_types(ty={:?})", ty);
843 let mut substituted_predicates = Vec::new();
844 ty.fold_with(&mut ty::fold::BottomUpFolder {
847 if let ty::Opaque(def_id, substs) = ty.kind {
848 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
849 let generics = tcx.generics_of(def_id);
850 // Only check named `impl Trait` types defined in this crate.
851 if generics.parent.is_none() && def_id.is_local() {
852 let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
853 if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
854 trace!("check_opaque_types: may define, generics={:#?}", generics);
855 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
856 for (subst, param) in substs.iter().zip(&generics.params) {
857 match subst.unpack() {
858 ty::subst::GenericArgKind::Type(ty) => match ty.kind {
860 // Prevent `fn foo() -> Foo<u32>` from being defining.
865 "non-defining opaque type use \
869 tcx.def_span(param.def_id),
871 "used non-generic type {} for \
880 ty::subst::GenericArgKind::Lifetime(region) => {
881 let param_span = tcx.def_span(param.def_id);
882 if let ty::ReStatic = region {
886 "non-defining opaque type use \
891 "cannot use static lifetime; use a bound lifetime \
892 instead or remove the lifetime parameter from the \
897 seen.entry(region).or_default().push(param_span);
901 ty::subst::GenericArgKind::Const(ct) => match ct.val {
902 ty::ConstKind::Param(_) => {}
907 "non-defining opaque type use \
911 tcx.def_span(param.def_id),
913 "used non-generic const {} for \
922 } // for (subst, param)
923 for (_, spans) in seen {
928 "non-defining opaque type use \
931 .span_note(spans, "lifetime used multiple times")
935 } // if may_define_opaque_type
937 // Now register the bounds on the parameters of the opaque type
938 // so the parameters given by the function need to fulfill them.
940 // type Foo<T: Bar> = impl Baz + 'static;
941 // fn foo<U>() -> Foo<U> { .. *}
945 // type Foo<T: Bar> = impl Baz + 'static;
946 // fn foo<U: Bar>() -> Foo<U> { .. *}
947 let predicates = tcx.predicates_of(def_id);
948 trace!("check_opaque_types: may define, predicates={:#?}", predicates,);
949 for &(pred, _) in predicates.predicates {
950 let substituted_pred = pred.subst(fcx.tcx, substs);
951 // Avoid duplication of predicates that contain no parameters, for example.
952 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
953 substituted_predicates.push(substituted_pred);
956 } // if is_named_opaque_type
963 substituted_predicates
966 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
967 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
968 of the previous types except `Self`)";
970 fn check_method_receiver<'fcx, 'tcx>(
971 fcx: &FnCtxt<'fcx, 'tcx>,
972 fn_sig: &hir::FnSig<'_>,
973 method: &ty::AssocItem,
976 // Check that the method has a valid receiver type, given the type `Self`.
977 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
979 if !method.method_has_self_argument {
983 let span = fn_sig.decl.inputs[0].span;
985 let sig = fcx.tcx.fn_sig(method.def_id);
986 let sig = fcx.normalize_associated_types_in(span, &sig);
987 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
989 debug!("check_method_receiver: sig={:?}", sig);
991 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
992 let self_ty = fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_ty));
994 let receiver_ty = sig.inputs()[0];
996 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
998 fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(receiver_ty));
1000 if fcx.tcx.features().arbitrary_self_types {
1001 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1002 // Report error; `arbitrary_self_types` was enabled.
1003 e0307(fcx, span, receiver_ty);
1006 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
1007 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
1008 // Report error; would have worked with `arbitrary_self_types`.
1010 &fcx.tcx.sess.parse_sess,
1011 sym::arbitrary_self_types,
1014 "`{}` cannot be used as the type of `self` without \
1015 the `arbitrary_self_types` feature",
1019 .help(HELP_FOR_SELF_TYPE)
1022 // Report error; would not have worked with `arbitrary_self_types`.
1023 e0307(fcx, span, receiver_ty);
1029 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
1031 fcx.tcx.sess.diagnostic(),
1034 "invalid `self` parameter type: {:?}",
1037 .note("type of `self` must be `Self` or a type that dereferences to it")
1038 .help(HELP_FOR_SELF_TYPE)
1042 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1043 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1044 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1045 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1046 /// `Deref<Target = self_ty>`.
1048 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1049 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1050 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1051 fn receiver_is_valid<'fcx, 'tcx>(
1052 fcx: &FnCtxt<'fcx, 'tcx>,
1054 receiver_ty: Ty<'tcx>,
1056 arbitrary_self_types_enabled: bool,
1058 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
1060 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
1062 // `self: Self` is always valid.
1063 if can_eq_self(receiver_ty) {
1064 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
1070 let mut autoderef = fcx.autoderef(span, receiver_ty);
1072 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1073 if arbitrary_self_types_enabled {
1074 autoderef = autoderef.include_raw_pointers();
1077 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1080 let receiver_trait_def_id = fcx.tcx.require_lang_item(lang_items::ReceiverTraitLangItem, None);
1082 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1084 if let Some((potential_self_ty, _)) = autoderef.next() {
1086 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1087 potential_self_ty, self_ty
1090 if can_eq_self(potential_self_ty) {
1091 autoderef.finalize(fcx);
1093 if let Some(mut err) =
1094 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
1101 // Without `feature(arbitrary_self_types)`, we require that each step in the
1102 // deref chain implement `receiver`
1103 if !arbitrary_self_types_enabled
1104 && !receiver_is_implemented(
1106 receiver_trait_def_id,
1115 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
1116 // If he receiver already has errors reported due to it, consider it valid to avoid
1117 // unnecessary errors (#58712).
1118 return receiver_ty.references_error();
1122 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1123 if !arbitrary_self_types_enabled
1124 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
1132 fn receiver_is_implemented(
1133 fcx: &FnCtxt<'_, 'tcx>,
1134 receiver_trait_def_id: DefId,
1135 cause: ObligationCause<'tcx>,
1136 receiver_ty: Ty<'tcx>,
1138 let trait_ref = ty::TraitRef {
1139 def_id: receiver_trait_def_id,
1140 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
1144 traits::Obligation::new(cause, fcx.param_env, trait_ref.without_const().to_predicate());
1146 if fcx.predicate_must_hold_modulo_regions(&obligation) {
1150 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1157 fn check_variances_for_type_defn<'tcx>(
1159 item: &hir::Item<'tcx>,
1160 hir_generics: &hir::Generics<'_>,
1162 let item_def_id = tcx.hir().local_def_id(item.hir_id);
1163 let ty = tcx.type_of(item_def_id);
1164 if tcx.has_error_field(ty) {
1168 let ty_predicates = tcx.predicates_of(item_def_id);
1169 assert_eq!(ty_predicates.parent, None);
1170 let variances = tcx.variances_of(item_def_id);
1172 let mut constrained_parameters: FxHashSet<_> = variances
1175 .filter(|&(_, &variance)| variance != ty::Bivariant)
1176 .map(|(index, _)| Parameter(index as u32))
1179 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
1181 for (index, _) in variances.iter().enumerate() {
1182 if constrained_parameters.contains(&Parameter(index as u32)) {
1186 let param = &hir_generics.params[index];
1189 hir::ParamName::Error => {}
1190 _ => report_bivariance(tcx, param.span, param.name.ident().name),
1195 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) {
1196 let mut err = error_392(tcx, span, param_name);
1198 let suggested_marker_id = tcx.lang_items().phantom_data();
1199 // Help is available only in presence of lang items.
1200 let msg = if let Some(def_id) = suggested_marker_id {
1202 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1204 tcx.def_path_str(def_id),
1207 format!("consider removing `{}` or referring to it in a field", param_name)
1213 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1215 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1216 let empty_env = ty::ParamEnv::empty();
1218 let def_id = fcx.tcx.hir().local_def_id(id);
1219 let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p).collect();
1220 // Check elaborated bounds.
1221 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1223 for pred in implied_obligations {
1224 // Match the existing behavior.
1225 if pred.is_global() && !pred.has_late_bound_regions() {
1226 let pred = fcx.normalize_associated_types_in(span, &pred);
1227 let obligation = traits::Obligation::new(
1228 traits::ObligationCause::new(span, id, traits::TrivialBound),
1232 fcx.register_predicate(obligation);
1236 fcx.select_all_obligations_or_error();
1239 pub struct CheckTypeWellFormedVisitor<'tcx> {
1243 impl CheckTypeWellFormedVisitor<'tcx> {
1244 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1245 CheckTypeWellFormedVisitor { tcx }
1249 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1250 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1251 debug!("visit_item: {:?}", i);
1252 let def_id = self.tcx.hir().local_def_id(i.hir_id);
1253 self.tcx.ensure().check_item_well_formed(def_id);
1256 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1257 debug!("visit_trait_item: {:?}", trait_item);
1258 let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1259 self.tcx.ensure().check_trait_item_well_formed(def_id);
1262 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1263 debug!("visit_impl_item: {:?}", impl_item);
1264 let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1265 self.tcx.ensure().check_impl_item_well_formed(def_id);
1269 ///////////////////////////////////////////////////////////////////////////
1272 struct AdtVariant<'tcx> {
1273 fields: Vec<AdtField<'tcx>>,
1276 struct AdtField<'tcx> {
1281 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1282 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1283 let fields = struct_def
1287 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1288 let field_ty = self.normalize_associated_types_in(field.span, &field_ty);
1289 let field_ty = self.resolve_vars_if_possible(&field_ty);
1290 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1291 AdtField { ty: field_ty, span: field.span }
1294 AdtVariant { fields }
1297 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1298 enum_def.variants.iter().map(|variant| self.non_enum_variant(&variant.data)).collect()
1301 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1302 match self.tcx.impl_trait_ref(impl_def_id) {
1303 Some(ref trait_ref) => {
1304 // Trait impl: take implied bounds from all types that
1305 // appear in the trait reference.
1306 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1307 trait_ref.substs.types().collect()
1311 // Inherent impl: take implied bounds from the `self` type.
1312 let self_ty = self.tcx.type_of(impl_def_id);
1313 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1320 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) -> DiagnosticBuilder<'_> {
1322 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1323 err.span_label(span, "unused parameter");