1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
4 use rustc::infer::opaque_types::may_define_opaque_type;
5 use rustc::middle::lang_items;
6 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
7 use rustc::ty::subst::{InternalSubsts, Subst};
8 use rustc::ty::{self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::ItemKind;
13 use errors::DiagnosticBuilder;
14 use rustc_span::symbol::sym;
17 use syntax::feature_gate;
20 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
22 use rustc_error_codes::*;
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: DefId) {
74 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
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)
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(_, _, defaultness, _, ref trait_ref, ref self_ty, _) => {
103 .impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
104 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
105 let polarity = tcx.impl_polarity(def_id);
106 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
107 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
110 ty::ImplPolarity::Positive => {
111 check_impl(tcx, item, self_ty, trait_ref);
113 ty::ImplPolarity::Negative => {
114 // FIXME(#27579): what amount of WF checking do we need for neg impls?
115 if trait_ref.is_some() && !is_auto {
120 "negative impls are only allowed for \
121 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_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
182 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) {
183 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
184 let impl_item = tcx.hir().expect_impl_item(hir_id);
186 let method_sig = match impl_item.kind {
187 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
191 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
194 fn check_associated_item(
198 sig_if_method: Option<&hir::FnSig<'_>>,
200 debug!("check_associated_item: {:?}", item_id);
202 let code = ObligationCauseCode::MiscObligation;
203 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
204 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
206 let (mut implied_bounds, self_ty) = match item.container {
207 ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
208 ty::ImplContainer(def_id) => {
209 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
214 ty::AssocKind::Const => {
215 let ty = fcx.tcx.type_of(item.def_id);
216 let ty = fcx.normalize_associated_types_in(span, &ty);
217 fcx.register_wf_obligation(ty, span, code.clone());
219 ty::AssocKind::Method => {
220 let sig = fcx.tcx.fn_sig(item.def_id);
221 let sig = fcx.normalize_associated_types_in(span, &sig);
222 check_fn_or_method(tcx, fcx, span, sig, item.def_id, &mut implied_bounds);
223 let sig_if_method = sig_if_method.expect("bad signature for method");
224 check_method_receiver(fcx, sig_if_method, &item, self_ty);
226 ty::AssocKind::Type => {
227 if item.defaultness.has_value() {
228 let ty = fcx.tcx.type_of(item.def_id);
229 let ty = fcx.normalize_associated_types_in(span, &ty);
230 fcx.register_wf_obligation(ty, span, code.clone());
233 ty::AssocKind::OpaqueTy => {
234 // Do nothing: opaque types check themselves.
242 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
243 for_id(tcx, item.hir_id, item.span)
246 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
247 let def_id = tcx.hir().local_def_id(id);
249 inherited: Inherited::build(tcx, def_id),
252 param_env: tcx.param_env(def_id),
256 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
258 ItemKind::Struct(..) => Some(AdtKind::Struct),
259 ItemKind::Union(..) => Some(AdtKind::Union),
260 ItemKind::Enum(..) => Some(AdtKind::Enum),
265 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
266 fn check_type_defn<'tcx, F>(
268 item: &hir::Item<'tcx>,
270 mut lookup_fields: F,
272 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
274 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
275 let variants = lookup_fields(fcx);
276 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
277 let packed = fcx.tcx.adt_def(def_id).repr.packed();
279 for variant in &variants {
280 // For DST, or when drop needs to copy things around, all
281 // intermediate types must be sized.
282 let needs_drop_copy = || {
284 let ty = variant.fields.last().unwrap().ty;
285 let ty = fcx.tcx.erase_regions(&ty);
286 if ty.has_local_value() {
289 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
290 // Just treat unresolved type expression as if it needs drop.
293 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
297 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
298 let unsized_len = if all_sized { 0 } else { 1 };
300 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
302 let last = idx == variant.fields.len() - 1;
305 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
306 traits::ObligationCause::new(
310 adt_kind: match item_adt_kind(&item.kind) {
320 // All field types must be well-formed.
321 for field in &variant.fields {
322 fcx.register_wf_obligation(
325 ObligationCauseCode::MiscObligation,
330 check_where_clauses(tcx, fcx, item.span, def_id, None);
332 // No implied bounds in a struct definition.
337 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
338 debug!("check_trait: {:?}", item.hir_id);
340 let trait_def_id = tcx.hir().local_def_id(item.hir_id);
342 let trait_def = tcx.trait_def(trait_def_id);
343 if trait_def.is_marker {
344 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
347 tcx.def_span(*associated_def_id),
349 "marker traits cannot have associated items",
355 for_item(tcx, item).with_fcx(|fcx, _| {
356 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
361 fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
362 for_item(tcx, item).with_fcx(|fcx, tcx| {
363 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
364 let sig = fcx.tcx.fn_sig(def_id);
365 let sig = fcx.normalize_associated_types_in(item.span, &sig);
366 let mut implied_bounds = vec![];
367 check_fn_or_method(tcx, fcx, item.span, sig, def_id, &mut implied_bounds);
372 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
373 debug!("check_item_type: {:?}", item_id);
375 for_id(tcx, item_id, ty_span).with_fcx(|fcx, tcx| {
376 let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
377 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
379 let mut forbid_unsized = true;
380 if allow_foreign_ty {
381 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
382 if let ty::Foreign(_) = tail.kind {
383 forbid_unsized = false;
387 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
391 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
392 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
396 // No implied bounds in a const, etc.
403 item: &'tcx hir::Item<'tcx>,
404 ast_self_ty: &hir::Ty<'_>,
405 ast_trait_ref: &Option<hir::TraitRef<'_>>,
407 debug!("check_impl: {:?}", item);
409 for_item(tcx, item).with_fcx(|fcx, tcx| {
410 let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
412 match *ast_trait_ref {
413 Some(ref ast_trait_ref) => {
414 // `#[rustc_reservation_impl]` impls are not real impls and
415 // therefore don't need to be WF (the trait's `Self: Trait` predicate
417 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
419 fcx.normalize_associated_types_in(ast_trait_ref.path.span, &trait_ref);
420 let obligations = traits::wf::trait_obligations(
425 ast_trait_ref.path.span,
428 for obligation in obligations {
429 fcx.register_predicate(obligation);
433 let self_ty = fcx.tcx.type_of(item_def_id);
434 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
435 fcx.register_wf_obligation(
438 ObligationCauseCode::MiscObligation,
443 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
445 fcx.impl_implied_bounds(item_def_id, item.span)
449 /// Checks where-clauses and inline bounds that are declared on `def_id`.
450 fn check_where_clauses<'tcx, 'fcx>(
452 fcx: &FnCtxt<'fcx, 'tcx>,
455 return_ty: Option<Ty<'tcx>>,
457 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
459 let predicates = fcx.tcx.predicates_of(def_id);
460 let generics = tcx.generics_of(def_id);
462 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
463 GenericParamDefKind::Type { has_default, .. } => {
464 has_default && def.index >= generics.parent_count as u32
469 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
470 // For example, this forbids the declaration:
472 // struct Foo<T = Vec<[u32]>> { .. }
474 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
475 for param in &generics.params {
476 if let GenericParamDefKind::Type { .. } = param.kind {
477 if is_our_default(¶m) {
478 let ty = fcx.tcx.type_of(param.def_id);
479 // Ignore dependent defaults -- that is, where the default of one type
480 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
481 // be sure if it will error or not as user might always specify the other.
482 if !ty.needs_subst() {
483 fcx.register_wf_obligation(
485 fcx.tcx.def_span(param.def_id),
486 ObligationCauseCode::MiscObligation,
493 // Check that trait predicates are WF when params are substituted by their defaults.
494 // We don't want to overly constrain the predicates that may be written but we want to
495 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
496 // Therefore we check if a predicate which contains a single type param
497 // with a concrete default is WF with that default substituted.
498 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
500 // First we build the defaulted substitution.
501 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
503 GenericParamDefKind::Lifetime => {
504 // All regions are identity.
505 fcx.tcx.mk_param_from_def(param)
508 GenericParamDefKind::Type { .. } => {
509 // If the param has a default, ...
510 if is_our_default(param) {
511 let default_ty = fcx.tcx.type_of(param.def_id);
512 // ... and it's not a dependent default, ...
513 if !default_ty.needs_subst() {
514 // ... then substitute it with the default.
515 return default_ty.into();
518 // Mark unwanted params as error.
519 fcx.tcx.types.err.into()
522 GenericParamDefKind::Const => {
523 // FIXME(const_generics:defaults)
524 fcx.tcx.consts.err.into()
529 // Now we build the substituted predicates.
530 let default_obligations = predicates
533 .flat_map(|&(pred, sp)| {
536 params: FxHashSet<u32>,
538 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
539 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
540 if let ty::Param(param) = t.kind {
541 self.params.insert(param.index);
543 t.super_visit_with(self)
546 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
550 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
551 if let ty::ConstKind::Param(param) = c.val {
552 self.params.insert(param.index);
554 c.super_visit_with(self)
557 let mut param_count = CountParams::default();
558 let has_region = pred.visit_with(&mut param_count);
559 let substituted_pred = pred.subst(fcx.tcx, substs);
560 // Don't check non-defaulted params, dependent defaults (including lifetimes)
561 // or preds with multiple params.
562 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
564 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
565 // Avoid duplication of predicates that contain no parameters, for example.
568 Some((substituted_pred, sp))
572 // Convert each of those into an obligation. So if you have
573 // something like `struct Foo<T: Copy = String>`, we would
574 // take that predicate `T: Copy`, substitute to `String: Copy`
575 // (actually that happens in the previous `flat_map` call),
576 // and then try to prove it (in this case, we'll fail).
578 // Note the subtle difference from how we handle `predicates`
579 // below: there, we are not trying to prove those predicates
580 // to be *true* but merely *well-formed*.
581 let pred = fcx.normalize_associated_types_in(sp, &pred);
583 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
584 traits::Obligation::new(cause, fcx.param_env, pred)
587 let mut predicates = predicates.instantiate_identity(fcx.tcx);
589 if let Some(return_ty) = return_ty {
590 predicates.predicates.extend(check_opaque_types(tcx, fcx, def_id, span, return_ty));
593 let predicates = fcx.normalize_associated_types_in(span, &predicates);
595 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
596 let wf_obligations = predicates
599 .flat_map(|p| traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, span));
601 for obligation in wf_obligations.chain(default_obligations) {
602 debug!("next obligation cause: {:?}", obligation.cause);
603 fcx.register_predicate(obligation);
607 fn check_fn_or_method<'fcx, 'tcx>(
609 fcx: &FnCtxt<'fcx, 'tcx>,
611 sig: ty::PolyFnSig<'tcx>,
613 implied_bounds: &mut Vec<Ty<'tcx>>,
615 let sig = fcx.normalize_associated_types_in(span, &sig);
616 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
618 for input_ty in sig.inputs() {
619 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
621 implied_bounds.extend(sig.inputs());
623 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::ReturnType);
625 // FIXME(#25759) return types should not be implied bounds
626 implied_bounds.push(sig.output());
628 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
631 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
632 /// laid for "higher-order pattern unification".
633 /// This ensures that inference is tractable.
634 /// In particular, definitions of opaque types can only use other generics as arguments,
635 /// and they cannot repeat an argument. Example:
638 /// type Foo<A, B> = impl Bar<A, B>;
640 /// // Okay -- `Foo` is applied to two distinct, generic types.
641 /// fn a<T, U>() -> Foo<T, U> { .. }
643 /// // Not okay -- `Foo` is applied to `T` twice.
644 /// fn b<T>() -> Foo<T, T> { .. }
646 /// // Not okay -- `Foo` is applied to a non-generic type.
647 /// fn b<T>() -> Foo<T, u32> { .. }
650 fn check_opaque_types<'fcx, 'tcx>(
652 fcx: &FnCtxt<'fcx, 'tcx>,
656 ) -> Vec<ty::Predicate<'tcx>> {
657 trace!("check_opaque_types(ty={:?})", ty);
658 let mut substituted_predicates = Vec::new();
659 ty.fold_with(&mut ty::fold::BottomUpFolder {
662 if let ty::Opaque(def_id, substs) = ty.kind {
663 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
664 let generics = tcx.generics_of(def_id);
665 // Only check named `impl Trait` types defined in this crate.
666 if generics.parent.is_none() && def_id.is_local() {
667 let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
668 if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
669 trace!("check_opaque_types: may define, generics={:#?}", generics);
670 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
671 for (subst, param) in substs.iter().zip(&generics.params) {
672 match subst.unpack() {
673 ty::subst::GenericArgKind::Type(ty) => match ty.kind {
675 // Prevent `fn foo() -> Foo<u32>` from being defining.
680 "non-defining opaque type use \
684 tcx.def_span(param.def_id),
686 "used non-generic type {} for \
695 ty::subst::GenericArgKind::Lifetime(region) => {
696 let param_span = tcx.def_span(param.def_id);
697 if let ty::ReStatic = region {
701 "non-defining opaque type use \
706 "cannot use static lifetime; use a bound lifetime \
707 instead or remove the lifetime parameter from the \
712 seen.entry(region).or_default().push(param_span);
716 ty::subst::GenericArgKind::Const(ct) => match ct.val {
717 ty::ConstKind::Param(_) => {}
722 "non-defining opaque type use \
726 tcx.def_span(param.def_id),
728 "used non-generic const {} for \
737 } // for (subst, param)
738 for (_, spans) in seen {
743 "non-defining opaque type use \
746 .span_note(spans, "lifetime used multiple times")
750 } // if may_define_opaque_type
752 // Now register the bounds on the parameters of the opaque type
753 // so the parameters given by the function need to fulfill them.
755 // type Foo<T: Bar> = impl Baz + 'static;
756 // fn foo<U>() -> Foo<U> { .. *}
760 // type Foo<T: Bar> = impl Baz + 'static;
761 // fn foo<U: Bar>() -> Foo<U> { .. *}
762 let predicates = tcx.predicates_of(def_id);
763 trace!("check_opaque_types: may define, predicates={:#?}", predicates,);
764 for &(pred, _) in predicates.predicates {
765 let substituted_pred = pred.subst(fcx.tcx, substs);
766 // Avoid duplication of predicates that contain no parameters, for example.
767 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
768 substituted_predicates.push(substituted_pred);
771 } // if is_named_opaque_type
778 substituted_predicates
781 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
782 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
783 of the previous types except `Self`)";
785 fn check_method_receiver<'fcx, 'tcx>(
786 fcx: &FnCtxt<'fcx, 'tcx>,
787 fn_sig: &hir::FnSig<'_>,
788 method: &ty::AssocItem,
791 // Check that the method has a valid receiver type, given the type `Self`.
792 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
794 if !method.method_has_self_argument {
798 let span = fn_sig.decl.inputs[0].span;
800 let sig = fcx.tcx.fn_sig(method.def_id);
801 let sig = fcx.normalize_associated_types_in(span, &sig);
802 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
804 debug!("check_method_receiver: sig={:?}", sig);
806 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
807 let self_ty = fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_ty));
809 let receiver_ty = sig.inputs()[0];
811 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
813 fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(receiver_ty));
815 if fcx.tcx.features().arbitrary_self_types {
816 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
817 // Report error; `arbitrary_self_types` was enabled.
818 e0307(fcx, span, receiver_ty);
821 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
822 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
823 // Report error; would have worked with `arbitrary_self_types`.
824 feature_gate::feature_err(
825 &fcx.tcx.sess.parse_sess,
826 sym::arbitrary_self_types,
829 "`{}` cannot be used as the type of `self` without \
830 the `arbitrary_self_types` feature",
834 .help(HELP_FOR_SELF_TYPE)
837 // Report error; would not have worked with `arbitrary_self_types`.
838 e0307(fcx, span, receiver_ty);
844 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
846 fcx.tcx.sess.diagnostic(),
849 "invalid `self` parameter type: {:?}",
852 .note("type of `self` must be `Self` or a type that dereferences to it")
853 .help(HELP_FOR_SELF_TYPE)
857 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
858 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
859 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
860 /// strict: `receiver_ty` must implement `Receiver` and directly implement
861 /// `Deref<Target = self_ty>`.
863 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
864 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
865 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
866 fn receiver_is_valid<'fcx, 'tcx>(
867 fcx: &FnCtxt<'fcx, 'tcx>,
869 receiver_ty: Ty<'tcx>,
871 arbitrary_self_types_enabled: bool,
873 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
875 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
877 // `self: Self` is always valid.
878 if can_eq_self(receiver_ty) {
879 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
885 let mut autoderef = fcx.autoderef(span, receiver_ty);
887 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
888 if arbitrary_self_types_enabled {
889 autoderef = autoderef.include_raw_pointers();
892 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
895 let receiver_trait_def_id = fcx.tcx.require_lang_item(lang_items::ReceiverTraitLangItem, None);
897 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
899 if let Some((potential_self_ty, _)) = autoderef.next() {
901 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
902 potential_self_ty, self_ty
905 if can_eq_self(potential_self_ty) {
906 autoderef.finalize(fcx);
908 if let Some(mut err) =
909 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
916 // Without `feature(arbitrary_self_types)`, we require that each step in the
917 // deref chain implement `receiver`
918 if !arbitrary_self_types_enabled
919 && !receiver_is_implemented(
921 receiver_trait_def_id,
930 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
931 // If he receiver already has errors reported due to it, consider it valid to avoid
932 // unnecessary errors (#58712).
933 return receiver_ty.references_error();
937 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
938 if !arbitrary_self_types_enabled
939 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
947 fn receiver_is_implemented(
948 fcx: &FnCtxt<'_, 'tcx>,
949 receiver_trait_def_id: DefId,
950 cause: ObligationCause<'tcx>,
951 receiver_ty: Ty<'tcx>,
953 let trait_ref = ty::TraitRef {
954 def_id: receiver_trait_def_id,
955 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
958 let obligation = traits::Obligation::new(cause, fcx.param_env, trait_ref.to_predicate());
960 if fcx.predicate_must_hold_modulo_regions(&obligation) {
964 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
971 fn check_variances_for_type_defn<'tcx>(
973 item: &hir::Item<'tcx>,
974 hir_generics: &hir::Generics<'_>,
976 let item_def_id = tcx.hir().local_def_id(item.hir_id);
977 let ty = tcx.type_of(item_def_id);
978 if tcx.has_error_field(ty) {
982 let ty_predicates = tcx.predicates_of(item_def_id);
983 assert_eq!(ty_predicates.parent, None);
984 let variances = tcx.variances_of(item_def_id);
986 let mut constrained_parameters: FxHashSet<_> = variances
989 .filter(|&(_, &variance)| variance != ty::Bivariant)
990 .map(|(index, _)| Parameter(index as u32))
993 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
995 for (index, _) in variances.iter().enumerate() {
996 if constrained_parameters.contains(&Parameter(index as u32)) {
1000 let param = &hir_generics.params[index];
1003 hir::ParamName::Error => {}
1004 _ => report_bivariance(tcx, param.span, param.name.ident().name),
1009 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) {
1010 let mut err = error_392(tcx, span, param_name);
1012 let suggested_marker_id = tcx.lang_items().phantom_data();
1013 // Help is available only in presence of lang items.
1014 let msg = if let Some(def_id) = suggested_marker_id {
1016 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1018 tcx.def_path_str(def_id),
1021 format!("consider removing `{}` or referring to it in a field", param_name)
1027 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1029 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1030 let empty_env = ty::ParamEnv::empty();
1032 let def_id = fcx.tcx.hir().local_def_id(id);
1033 let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p).collect();
1034 // Check elaborated bounds.
1035 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1037 for pred in implied_obligations {
1038 // Match the existing behavior.
1039 if pred.is_global() && !pred.has_late_bound_regions() {
1040 let pred = fcx.normalize_associated_types_in(span, &pred);
1041 let obligation = traits::Obligation::new(
1042 traits::ObligationCause::new(span, id, traits::TrivialBound),
1046 fcx.register_predicate(obligation);
1050 fcx.select_all_obligations_or_error();
1053 pub struct CheckTypeWellFormedVisitor<'tcx> {
1057 impl CheckTypeWellFormedVisitor<'tcx> {
1058 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1059 CheckTypeWellFormedVisitor { tcx }
1063 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1064 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1065 debug!("visit_item: {:?}", i);
1066 let def_id = self.tcx.hir().local_def_id(i.hir_id);
1067 self.tcx.ensure().check_item_well_formed(def_id);
1070 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1071 debug!("visit_trait_item: {:?}", trait_item);
1072 let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1073 self.tcx.ensure().check_trait_item_well_formed(def_id);
1076 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1077 debug!("visit_impl_item: {:?}", impl_item);
1078 let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1079 self.tcx.ensure().check_impl_item_well_formed(def_id);
1083 ///////////////////////////////////////////////////////////////////////////
1086 struct AdtVariant<'tcx> {
1087 fields: Vec<AdtField<'tcx>>,
1090 struct AdtField<'tcx> {
1095 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1096 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1097 let fields = struct_def
1101 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1102 let field_ty = self.normalize_associated_types_in(field.span, &field_ty);
1103 let field_ty = self.resolve_vars_if_possible(&field_ty);
1104 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1105 AdtField { ty: field_ty, span: field.span }
1108 AdtVariant { fields }
1111 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1112 enum_def.variants.iter().map(|variant| self.non_enum_variant(&variant.data)).collect()
1115 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1116 match self.tcx.impl_trait_ref(impl_def_id) {
1117 Some(ref trait_ref) => {
1118 // Trait impl: take implied bounds from all types that
1119 // appear in the trait reference.
1120 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1121 trait_ref.substs.types().collect()
1125 // Inherent impl: take implied bounds from the `self` type.
1126 let self_ty = self.tcx.type_of(impl_def_id);
1127 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1134 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) -> DiagnosticBuilder<'_> {
1136 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1137 err.span_label(span, "unused parameter");