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::session::parse::feature_err;
7 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
8 use rustc::ty::subst::{InternalSubsts, Subst};
9 use rustc::ty::{self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable};
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_errors::{struct_span_err, DiagnosticBuilder};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::ItemKind;
14 use rustc_span::symbol::sym;
19 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
21 /// Helper type of a temporary returned by `.for_item(...)`.
22 /// This is necessary because we can't write the following bound:
25 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
27 struct CheckWfFcxBuilder<'tcx> {
28 inherited: super::InheritedBuilder<'tcx>,
31 param_env: ty::ParamEnv<'tcx>,
34 impl<'tcx> CheckWfFcxBuilder<'tcx> {
35 fn with_fcx<F>(&mut self, f: F)
37 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>, TyCtxt<'tcx>) -> Vec<Ty<'tcx>>,
41 let param_env = self.param_env;
42 self.inherited.enter(|inh| {
43 let fcx = FnCtxt::new(&inh, param_env, id);
44 if !inh.tcx.features().trivial_bounds {
45 // As predicates are cached rather than obligations, this
46 // needsto be called first so that they are checked with an
48 check_false_global_bounds(&fcx, span, id);
50 let wf_tys = f(&fcx, fcx.tcx);
51 fcx.select_all_obligations_or_error();
52 fcx.regionck_item(id, span, &wf_tys);
57 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
58 /// well-formed, meaning that they do not require any constraints not declared in the struct
59 /// definition itself. For example, this definition would be illegal:
62 /// struct Ref<'a, T> { x: &'a T }
65 /// because the type did not declare that `T:'a`.
67 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
68 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
70 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
71 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
72 let item = tcx.hir().expect_item(hir_id);
75 "check_item_well_formed(it.hir_id={:?}, it.name={})",
77 tcx.def_path_str(def_id)
81 // Right now we check that every default trait implementation
82 // has an implementation of itself. Basically, a case like:
84 // impl Trait for T {}
86 // has a requirement of `T: Trait` which was required for default
87 // method implementations. Although this could be improved now that
88 // there's a better infrastructure in place for this, it's being left
89 // for a follow-up work.
91 // Since there's such a requirement, we need to check *just* positive
92 // implementations, otherwise things like:
94 // impl !Send for T {}
96 // won't be allowed unless there's an *explicit* implementation of `Send`
98 hir::ItemKind::Impl { defaultness, ref of_trait, ref self_ty, .. } => {
100 .impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
101 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
102 let polarity = tcx.impl_polarity(def_id);
103 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
104 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
107 ty::ImplPolarity::Positive => {
108 check_impl(tcx, item, self_ty, of_trait);
110 ty::ImplPolarity::Negative => {
111 // FIXME(#27579): what amount of WF checking do we need for neg impls?
112 if of_trait.is_some() && !is_auto {
117 "negative impls are only allowed for \
118 auto traits (e.g., `Send` and `Sync`)"
123 ty::ImplPolarity::Reservation => {
124 // FIXME: what amount of WF checking do we need for reservation impls?
128 hir::ItemKind::Fn(..) => {
129 check_item_fn(tcx, item);
131 hir::ItemKind::Static(ref ty, ..) => {
132 check_item_type(tcx, item.hir_id, ty.span, false);
134 hir::ItemKind::Const(ref ty, ..) => {
135 check_item_type(tcx, item.hir_id, ty.span, false);
137 hir::ItemKind::ForeignMod(ref module) => {
138 for it in module.items.iter() {
139 if let hir::ForeignItemKind::Static(ref ty, ..) = it.kind {
140 check_item_type(tcx, it.hir_id, ty.span, true);
144 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
145 check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
147 check_variances_for_type_defn(tcx, item, ast_generics);
149 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
150 check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
152 check_variances_for_type_defn(tcx, item, ast_generics);
154 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
155 check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
157 check_variances_for_type_defn(tcx, item, ast_generics);
159 hir::ItemKind::Trait(..) => {
160 check_trait(tcx, item);
162 hir::ItemKind::TraitAlias(..) => {
163 check_trait(tcx, item);
169 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: DefId) {
170 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
171 let trait_item = tcx.hir().expect_trait_item(hir_id);
173 let method_sig = match trait_item.kind {
174 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
177 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
180 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) {
181 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
182 let impl_item = tcx.hir().expect_impl_item(hir_id);
184 let method_sig = match impl_item.kind {
185 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
189 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
192 fn check_associated_item(
196 sig_if_method: Option<&hir::FnSig<'_>>,
198 debug!("check_associated_item: {:?}", item_id);
200 let code = ObligationCauseCode::MiscObligation;
201 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
202 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
204 let (mut implied_bounds, self_ty) = match item.container {
205 ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
206 ty::ImplContainer(def_id) => {
207 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
212 ty::AssocKind::Const => {
213 let ty = fcx.tcx.type_of(item.def_id);
214 let ty = fcx.normalize_associated_types_in(span, &ty);
215 fcx.register_wf_obligation(ty, span, code.clone());
217 ty::AssocKind::Method => {
218 let sig = fcx.tcx.fn_sig(item.def_id);
219 let sig = fcx.normalize_associated_types_in(span, &sig);
220 check_fn_or_method(tcx, fcx, span, sig, item.def_id, &mut implied_bounds);
221 let sig_if_method = sig_if_method.expect("bad signature for method");
222 check_method_receiver(fcx, sig_if_method, &item, self_ty);
224 ty::AssocKind::Type => {
225 if item.defaultness.has_value() {
226 let ty = fcx.tcx.type_of(item.def_id);
227 let ty = fcx.normalize_associated_types_in(span, &ty);
228 fcx.register_wf_obligation(ty, span, code.clone());
231 ty::AssocKind::OpaqueTy => {
232 // Do nothing: opaque types check themselves.
240 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
241 for_id(tcx, item.hir_id, item.span)
244 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
245 let def_id = tcx.hir().local_def_id(id);
247 inherited: Inherited::build(tcx, def_id),
250 param_env: tcx.param_env(def_id),
254 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
256 ItemKind::Struct(..) => Some(AdtKind::Struct),
257 ItemKind::Union(..) => Some(AdtKind::Union),
258 ItemKind::Enum(..) => Some(AdtKind::Enum),
263 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
264 fn check_type_defn<'tcx, F>(
266 item: &hir::Item<'tcx>,
268 mut lookup_fields: F,
270 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
272 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
273 let variants = lookup_fields(fcx);
274 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
275 let packed = fcx.tcx.adt_def(def_id).repr.packed();
277 for variant in &variants {
278 // For DST, or when drop needs to copy things around, all
279 // intermediate types must be sized.
280 let needs_drop_copy = || {
282 let ty = variant.fields.last().unwrap().ty;
283 let ty = fcx.tcx.erase_regions(&ty);
284 if ty.has_local_value() {
287 .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
288 // Just treat unresolved type expression as if it needs drop.
291 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
295 let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
296 let unsized_len = if all_sized { 0 } else { 1 };
298 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
300 let last = idx == variant.fields.len() - 1;
303 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
304 traits::ObligationCause::new(
308 adt_kind: match item_adt_kind(&item.kind) {
318 // All field types must be well-formed.
319 for field in &variant.fields {
320 fcx.register_wf_obligation(
323 ObligationCauseCode::MiscObligation,
328 check_where_clauses(tcx, fcx, item.span, def_id, None);
330 // No implied bounds in a struct definition.
335 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
336 debug!("check_trait: {:?}", item.hir_id);
338 let trait_def_id = tcx.hir().local_def_id(item.hir_id);
340 let trait_def = tcx.trait_def(trait_def_id);
341 if trait_def.is_marker {
342 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
345 tcx.def_span(*associated_def_id),
347 "marker traits cannot have associated items",
353 for_item(tcx, item).with_fcx(|fcx, _| {
354 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
359 fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
360 for_item(tcx, item).with_fcx(|fcx, tcx| {
361 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
362 let sig = fcx.tcx.fn_sig(def_id);
363 let sig = fcx.normalize_associated_types_in(item.span, &sig);
364 let mut implied_bounds = vec![];
365 check_fn_or_method(tcx, fcx, item.span, sig, def_id, &mut implied_bounds);
370 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
371 debug!("check_item_type: {:?}", item_id);
373 for_id(tcx, item_id, ty_span).with_fcx(|fcx, tcx| {
374 let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
375 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
377 let mut forbid_unsized = true;
378 if allow_foreign_ty {
379 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
380 if let ty::Foreign(_) = tail.kind {
381 forbid_unsized = false;
385 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
389 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
390 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
394 // No implied bounds in a const, etc.
401 item: &'tcx hir::Item<'tcx>,
402 ast_self_ty: &hir::Ty<'_>,
403 ast_trait_ref: &Option<hir::TraitRef<'_>>,
405 debug!("check_impl: {:?}", item);
407 for_item(tcx, item).with_fcx(|fcx, tcx| {
408 let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
410 match *ast_trait_ref {
411 Some(ref ast_trait_ref) => {
412 // `#[rustc_reservation_impl]` impls are not real impls and
413 // therefore don't need to be WF (the trait's `Self: Trait` predicate
415 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
417 fcx.normalize_associated_types_in(ast_trait_ref.path.span, &trait_ref);
418 let obligations = traits::wf::trait_obligations(
423 ast_trait_ref.path.span,
426 for obligation in obligations {
427 fcx.register_predicate(obligation);
431 let self_ty = fcx.tcx.type_of(item_def_id);
432 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
433 fcx.register_wf_obligation(
436 ObligationCauseCode::MiscObligation,
441 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
443 fcx.impl_implied_bounds(item_def_id, item.span)
447 /// Checks where-clauses and inline bounds that are declared on `def_id`.
448 fn check_where_clauses<'tcx, 'fcx>(
450 fcx: &FnCtxt<'fcx, 'tcx>,
453 return_ty: Option<Ty<'tcx>>,
455 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
457 let predicates = fcx.tcx.predicates_of(def_id);
458 let generics = tcx.generics_of(def_id);
460 let is_our_default = |def: &ty::GenericParamDef| match def.kind {
461 GenericParamDefKind::Type { has_default, .. } => {
462 has_default && def.index >= generics.parent_count as u32
467 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
468 // For example, this forbids the declaration:
470 // struct Foo<T = Vec<[u32]>> { .. }
472 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
473 for param in &generics.params {
474 if let GenericParamDefKind::Type { .. } = param.kind {
475 if is_our_default(¶m) {
476 let ty = fcx.tcx.type_of(param.def_id);
477 // Ignore dependent defaults -- that is, where the default of one type
478 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
479 // be sure if it will error or not as user might always specify the other.
480 if !ty.needs_subst() {
481 fcx.register_wf_obligation(
483 fcx.tcx.def_span(param.def_id),
484 ObligationCauseCode::MiscObligation,
491 // Check that trait predicates are WF when params are substituted by their defaults.
492 // We don't want to overly constrain the predicates that may be written but we want to
493 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
494 // Therefore we check if a predicate which contains a single type param
495 // with a concrete default is WF with that default substituted.
496 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
498 // First we build the defaulted substitution.
499 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
501 GenericParamDefKind::Lifetime => {
502 // All regions are identity.
503 fcx.tcx.mk_param_from_def(param)
506 GenericParamDefKind::Type { .. } => {
507 // If the param has a default, ...
508 if is_our_default(param) {
509 let default_ty = fcx.tcx.type_of(param.def_id);
510 // ... and it's not a dependent default, ...
511 if !default_ty.needs_subst() {
512 // ... then substitute it with the default.
513 return default_ty.into();
516 // Mark unwanted params as error.
517 fcx.tcx.types.err.into()
520 GenericParamDefKind::Const => {
521 // FIXME(const_generics:defaults)
522 fcx.tcx.consts.err.into()
527 // Now we build the substituted predicates.
528 let default_obligations = predicates
531 .flat_map(|&(pred, sp)| {
534 params: FxHashSet<u32>,
536 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
537 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
538 if let ty::Param(param) = t.kind {
539 self.params.insert(param.index);
541 t.super_visit_with(self)
544 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
548 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
549 if let ty::ConstKind::Param(param) = c.val {
550 self.params.insert(param.index);
552 c.super_visit_with(self)
555 let mut param_count = CountParams::default();
556 let has_region = pred.visit_with(&mut param_count);
557 let substituted_pred = pred.subst(fcx.tcx, substs);
558 // Don't check non-defaulted params, dependent defaults (including lifetimes)
559 // or preds with multiple params.
560 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
562 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
563 // Avoid duplication of predicates that contain no parameters, for example.
566 Some((substituted_pred, sp))
570 // Convert each of those into an obligation. So if you have
571 // something like `struct Foo<T: Copy = String>`, we would
572 // take that predicate `T: Copy`, substitute to `String: Copy`
573 // (actually that happens in the previous `flat_map` call),
574 // and then try to prove it (in this case, we'll fail).
576 // Note the subtle difference from how we handle `predicates`
577 // below: there, we are not trying to prove those predicates
578 // to be *true* but merely *well-formed*.
579 let pred = fcx.normalize_associated_types_in(sp, &pred);
581 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
582 traits::Obligation::new(cause, fcx.param_env, pred)
585 let mut predicates = predicates.instantiate_identity(fcx.tcx);
587 if let Some(return_ty) = return_ty {
588 predicates.predicates.extend(check_opaque_types(tcx, fcx, def_id, span, return_ty));
591 let predicates = fcx.normalize_associated_types_in(span, &predicates);
593 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
594 let wf_obligations = predicates
597 .flat_map(|p| traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, span));
599 for obligation in wf_obligations.chain(default_obligations) {
600 debug!("next obligation cause: {:?}", obligation.cause);
601 fcx.register_predicate(obligation);
605 fn check_fn_or_method<'fcx, 'tcx>(
607 fcx: &FnCtxt<'fcx, 'tcx>,
609 sig: ty::PolyFnSig<'tcx>,
611 implied_bounds: &mut Vec<Ty<'tcx>>,
613 let sig = fcx.normalize_associated_types_in(span, &sig);
614 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
616 for input_ty in sig.inputs() {
617 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
619 implied_bounds.extend(sig.inputs());
621 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::ReturnType);
623 // FIXME(#25759) return types should not be implied bounds
624 implied_bounds.push(sig.output());
626 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
629 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
630 /// laid for "higher-order pattern unification".
631 /// This ensures that inference is tractable.
632 /// In particular, definitions of opaque types can only use other generics as arguments,
633 /// and they cannot repeat an argument. Example:
636 /// type Foo<A, B> = impl Bar<A, B>;
638 /// // Okay -- `Foo` is applied to two distinct, generic types.
639 /// fn a<T, U>() -> Foo<T, U> { .. }
641 /// // Not okay -- `Foo` is applied to `T` twice.
642 /// fn b<T>() -> Foo<T, T> { .. }
644 /// // Not okay -- `Foo` is applied to a non-generic type.
645 /// fn b<T>() -> Foo<T, u32> { .. }
648 fn check_opaque_types<'fcx, 'tcx>(
650 fcx: &FnCtxt<'fcx, 'tcx>,
654 ) -> Vec<ty::Predicate<'tcx>> {
655 trace!("check_opaque_types(ty={:?})", ty);
656 let mut substituted_predicates = Vec::new();
657 ty.fold_with(&mut ty::fold::BottomUpFolder {
660 if let ty::Opaque(def_id, substs) = ty.kind {
661 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
662 let generics = tcx.generics_of(def_id);
663 // Only check named `impl Trait` types defined in this crate.
664 if generics.parent.is_none() && def_id.is_local() {
665 let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
666 if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
667 trace!("check_opaque_types: may define, generics={:#?}", generics);
668 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
669 for (subst, param) in substs.iter().zip(&generics.params) {
670 match subst.unpack() {
671 ty::subst::GenericArgKind::Type(ty) => match ty.kind {
673 // Prevent `fn foo() -> Foo<u32>` from being defining.
678 "non-defining opaque type use \
682 tcx.def_span(param.def_id),
684 "used non-generic type {} for \
693 ty::subst::GenericArgKind::Lifetime(region) => {
694 let param_span = tcx.def_span(param.def_id);
695 if let ty::ReStatic = region {
699 "non-defining opaque type use \
704 "cannot use static lifetime; use a bound lifetime \
705 instead or remove the lifetime parameter from the \
710 seen.entry(region).or_default().push(param_span);
714 ty::subst::GenericArgKind::Const(ct) => match ct.val {
715 ty::ConstKind::Param(_) => {}
720 "non-defining opaque type use \
724 tcx.def_span(param.def_id),
726 "used non-generic const {} for \
735 } // for (subst, param)
736 for (_, spans) in seen {
741 "non-defining opaque type use \
744 .span_note(spans, "lifetime used multiple times")
748 } // if may_define_opaque_type
750 // Now register the bounds on the parameters of the opaque type
751 // so the parameters given by the function need to fulfill them.
753 // type Foo<T: Bar> = impl Baz + 'static;
754 // fn foo<U>() -> Foo<U> { .. *}
758 // type Foo<T: Bar> = impl Baz + 'static;
759 // fn foo<U: Bar>() -> Foo<U> { .. *}
760 let predicates = tcx.predicates_of(def_id);
761 trace!("check_opaque_types: may define, predicates={:#?}", predicates,);
762 for &(pred, _) in predicates.predicates {
763 let substituted_pred = pred.subst(fcx.tcx, substs);
764 // Avoid duplication of predicates that contain no parameters, for example.
765 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
766 substituted_predicates.push(substituted_pred);
769 } // if is_named_opaque_type
776 substituted_predicates
779 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
780 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
781 of the previous types except `Self`)";
783 fn check_method_receiver<'fcx, 'tcx>(
784 fcx: &FnCtxt<'fcx, 'tcx>,
785 fn_sig: &hir::FnSig<'_>,
786 method: &ty::AssocItem,
789 // Check that the method has a valid receiver type, given the type `Self`.
790 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
792 if !method.method_has_self_argument {
796 let span = fn_sig.decl.inputs[0].span;
798 let sig = fcx.tcx.fn_sig(method.def_id);
799 let sig = fcx.normalize_associated_types_in(span, &sig);
800 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
802 debug!("check_method_receiver: sig={:?}", sig);
804 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
805 let self_ty = fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_ty));
807 let receiver_ty = sig.inputs()[0];
809 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
811 fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(receiver_ty));
813 if fcx.tcx.features().arbitrary_self_types {
814 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
815 // Report error; `arbitrary_self_types` was enabled.
816 e0307(fcx, span, receiver_ty);
819 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
820 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
821 // Report error; would have worked with `arbitrary_self_types`.
823 &fcx.tcx.sess.parse_sess,
824 sym::arbitrary_self_types,
827 "`{}` cannot be used as the type of `self` without \
828 the `arbitrary_self_types` feature",
832 .help(HELP_FOR_SELF_TYPE)
835 // Report error; would not have worked with `arbitrary_self_types`.
836 e0307(fcx, span, receiver_ty);
842 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
844 fcx.tcx.sess.diagnostic(),
847 "invalid `self` parameter type: {:?}",
850 .note("type of `self` must be `Self` or a type that dereferences to it")
851 .help(HELP_FOR_SELF_TYPE)
855 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
856 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
857 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
858 /// strict: `receiver_ty` must implement `Receiver` and directly implement
859 /// `Deref<Target = self_ty>`.
861 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
862 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
863 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
864 fn receiver_is_valid<'fcx, 'tcx>(
865 fcx: &FnCtxt<'fcx, 'tcx>,
867 receiver_ty: Ty<'tcx>,
869 arbitrary_self_types_enabled: bool,
871 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
873 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
875 // `self: Self` is always valid.
876 if can_eq_self(receiver_ty) {
877 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
883 let mut autoderef = fcx.autoderef(span, receiver_ty);
885 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
886 if arbitrary_self_types_enabled {
887 autoderef = autoderef.include_raw_pointers();
890 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
893 let receiver_trait_def_id = fcx.tcx.require_lang_item(lang_items::ReceiverTraitLangItem, None);
895 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
897 if let Some((potential_self_ty, _)) = autoderef.next() {
899 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
900 potential_self_ty, self_ty
903 if can_eq_self(potential_self_ty) {
904 autoderef.finalize(fcx);
906 if let Some(mut err) =
907 fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
914 // Without `feature(arbitrary_self_types)`, we require that each step in the
915 // deref chain implement `receiver`
916 if !arbitrary_self_types_enabled
917 && !receiver_is_implemented(
919 receiver_trait_def_id,
928 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
929 // If he receiver already has errors reported due to it, consider it valid to avoid
930 // unnecessary errors (#58712).
931 return receiver_ty.references_error();
935 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
936 if !arbitrary_self_types_enabled
937 && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
945 fn receiver_is_implemented(
946 fcx: &FnCtxt<'_, 'tcx>,
947 receiver_trait_def_id: DefId,
948 cause: ObligationCause<'tcx>,
949 receiver_ty: Ty<'tcx>,
951 let trait_ref = ty::TraitRef {
952 def_id: receiver_trait_def_id,
953 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
956 let obligation = traits::Obligation::new(cause, fcx.param_env, trait_ref.to_predicate());
958 if fcx.predicate_must_hold_modulo_regions(&obligation) {
962 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
969 fn check_variances_for_type_defn<'tcx>(
971 item: &hir::Item<'tcx>,
972 hir_generics: &hir::Generics<'_>,
974 let item_def_id = tcx.hir().local_def_id(item.hir_id);
975 let ty = tcx.type_of(item_def_id);
976 if tcx.has_error_field(ty) {
980 let ty_predicates = tcx.predicates_of(item_def_id);
981 assert_eq!(ty_predicates.parent, None);
982 let variances = tcx.variances_of(item_def_id);
984 let mut constrained_parameters: FxHashSet<_> = variances
987 .filter(|&(_, &variance)| variance != ty::Bivariant)
988 .map(|(index, _)| Parameter(index as u32))
991 identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
993 for (index, _) in variances.iter().enumerate() {
994 if constrained_parameters.contains(&Parameter(index as u32)) {
998 let param = &hir_generics.params[index];
1001 hir::ParamName::Error => {}
1002 _ => report_bivariance(tcx, param.span, param.name.ident().name),
1007 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) {
1008 let mut err = error_392(tcx, span, param_name);
1010 let suggested_marker_id = tcx.lang_items().phantom_data();
1011 // Help is available only in presence of lang items.
1012 let msg = if let Some(def_id) = suggested_marker_id {
1014 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1016 tcx.def_path_str(def_id),
1019 format!("consider removing `{}` or referring to it in a field", param_name)
1025 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1027 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1028 let empty_env = ty::ParamEnv::empty();
1030 let def_id = fcx.tcx.hir().local_def_id(id);
1031 let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p).collect();
1032 // Check elaborated bounds.
1033 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1035 for pred in implied_obligations {
1036 // Match the existing behavior.
1037 if pred.is_global() && !pred.has_late_bound_regions() {
1038 let pred = fcx.normalize_associated_types_in(span, &pred);
1039 let obligation = traits::Obligation::new(
1040 traits::ObligationCause::new(span, id, traits::TrivialBound),
1044 fcx.register_predicate(obligation);
1048 fcx.select_all_obligations_or_error();
1051 pub struct CheckTypeWellFormedVisitor<'tcx> {
1055 impl CheckTypeWellFormedVisitor<'tcx> {
1056 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1057 CheckTypeWellFormedVisitor { tcx }
1061 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1062 fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1063 debug!("visit_item: {:?}", i);
1064 let def_id = self.tcx.hir().local_def_id(i.hir_id);
1065 self.tcx.ensure().check_item_well_formed(def_id);
1068 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1069 debug!("visit_trait_item: {:?}", trait_item);
1070 let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1071 self.tcx.ensure().check_trait_item_well_formed(def_id);
1074 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1075 debug!("visit_impl_item: {:?}", impl_item);
1076 let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1077 self.tcx.ensure().check_impl_item_well_formed(def_id);
1081 ///////////////////////////////////////////////////////////////////////////
1084 struct AdtVariant<'tcx> {
1085 fields: Vec<AdtField<'tcx>>,
1088 struct AdtField<'tcx> {
1093 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1094 fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1095 let fields = struct_def
1099 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1100 let field_ty = self.normalize_associated_types_in(field.span, &field_ty);
1101 let field_ty = self.resolve_vars_if_possible(&field_ty);
1102 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1103 AdtField { ty: field_ty, span: field.span }
1106 AdtVariant { fields }
1109 fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1110 enum_def.variants.iter().map(|variant| self.non_enum_variant(&variant.data)).collect()
1113 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1114 match self.tcx.impl_trait_ref(impl_def_id) {
1115 Some(ref trait_ref) => {
1116 // Trait impl: take implied bounds from all types that
1117 // appear in the trait reference.
1118 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1119 trait_ref.substs.types().collect()
1123 // Inherent impl: take implied bounds from the `self` type.
1124 let self_ty = self.tcx.type_of(impl_def_id);
1125 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1132 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) -> DiagnosticBuilder<'_> {
1134 struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1135 err.span_label(span, "unused parameter");