1 use crate::check::{Inherited, FnCtxt};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
4 use crate::hir::def_id::DefId;
5 use rustc::traits::{self, ObligationCauseCode};
6 use rustc::ty::{self, Ty, TyCtxt, GenericParamDefKind, TypeFoldable, ToPredicate};
7 use rustc::ty::subst::{Subst, InternalSubsts};
8 use rustc::util::nodemap::{FxHashSet, FxHashMap};
9 use rustc::mir::interpret::ConstValue;
10 use rustc::middle::lang_items;
11 use rustc::infer::opaque_types::may_define_opaque_type;
14 use syntax::feature_gate::{self, GateIssue};
16 use syntax::symbol::sym;
17 use errors::{DiagnosticBuilder, DiagnosticId};
19 use rustc::hir::itemlikevisit::ParItemLikeVisitor;
22 /// Helper type of a temporary returned by `.for_item(...)`.
23 /// This is necessary because we can't write the following bound:
26 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
28 struct CheckWfFcxBuilder<'tcx> {
29 inherited: super::InheritedBuilder<'tcx>,
32 param_env: ty::ParamEnv<'tcx>,
35 impl<'tcx> CheckWfFcxBuilder<'tcx> {
36 fn with_fcx<F>(&mut self, f: F)
38 F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>, TyCtxt<'tcx>) -> Vec<Ty<'tcx>>,
42 let param_env = self.param_env;
43 self.inherited.enter(|inh| {
44 let fcx = FnCtxt::new(&inh, param_env, id);
45 if !inh.tcx.features().trivial_bounds {
46 // As predicates are cached rather than obligations, this
47 // needsto be called first so that they are checked with an
49 check_false_global_bounds(&fcx, span, id);
51 let wf_tys = f(&fcx, fcx.tcx.global_tcx());
52 fcx.select_all_obligations_or_error();
53 fcx.regionck_item(id, span, &wf_tys);
58 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
59 /// well-formed, meaning that they do not require any constraints not declared in the struct
60 /// definition itself. For example, this definition would be illegal:
63 /// struct Ref<'a, T> { x: &'a T }
66 /// because the type did not declare that `T:'a`.
68 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
69 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
71 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
72 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
73 let item = tcx.hir().expect_item(hir_id);
75 debug!("check_item_well_formed(it.hir_id={:?}, it.name={})",
77 tcx.def_path_str(def_id));
80 // Right now we check that every default trait implementation
81 // has an implementation of itself. Basically, a case like:
83 // impl Trait for T {}
85 // has a requirement of `T: Trait` which was required for default
86 // method implementations. Although this could be improved now that
87 // there's a better infrastructure in place for this, it's being left
88 // for a follow-up work.
90 // Since there's such a requirement, we need to check *just* positive
91 // implementations, otherwise things like:
93 // impl !Send for T {}
95 // won't be allowed unless there's an *explicit* implementation of `Send`
97 hir::ItemKind::Impl(_, _, defaultness, _, ref trait_ref, ref self_ty, _) => {
98 let is_auto = tcx.impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
99 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
100 let polarity = tcx.impl_polarity(def_id);
101 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
102 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
105 ty::ImplPolarity::Positive => {
106 check_impl(tcx, item, self_ty, trait_ref);
108 ty::ImplPolarity::Negative => {
109 // FIXME(#27579): what amount of WF checking do we need for neg impls?
110 if trait_ref.is_some() && !is_auto {
111 span_err!(tcx.sess, item.span, E0192,
112 "negative impls are only allowed for \
113 auto traits (e.g., `Send` and `Sync`)")
116 ty::ImplPolarity::Reservation => {
117 // FIXME: what amount of WF checking do we need for reservation impls?
121 hir::ItemKind::Fn(..) => {
122 check_item_fn(tcx, item);
124 hir::ItemKind::Static(ref ty, ..) => {
125 check_item_type(tcx, item.hir_id, ty.span, false);
127 hir::ItemKind::Const(ref ty, ..) => {
128 check_item_type(tcx, item.hir_id, ty.span, false);
130 hir::ItemKind::ForeignMod(ref module) => for it in module.items.iter() {
131 if let hir::ForeignItemKind::Static(ref ty, ..) = it.node {
132 check_item_type(tcx, it.hir_id, ty.span, true);
135 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
136 check_type_defn(tcx, item, false, |fcx| {
137 vec![fcx.non_enum_variant(struct_def)]
140 check_variances_for_type_defn(tcx, item, ast_generics);
142 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
143 check_type_defn(tcx, item, true, |fcx| {
144 vec![fcx.non_enum_variant(struct_def)]
147 check_variances_for_type_defn(tcx, item, ast_generics);
149 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
150 check_type_defn(tcx, item, true, |fcx| {
151 fcx.enum_variants(enum_def)
154 check_variances_for_type_defn(tcx, item, ast_generics);
156 hir::ItemKind::Trait(..) => {
157 check_trait(tcx, item);
159 hir::ItemKind::TraitAlias(..) => {
160 check_trait(tcx, item);
166 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: DefId) {
167 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
168 let trait_item = tcx.hir().expect_trait_item(hir_id);
170 let method_sig = match trait_item.kind {
171 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
174 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
177 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) {
178 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
179 let impl_item = tcx.hir().expect_impl_item(hir_id);
181 let method_sig = match impl_item.kind {
182 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
185 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
188 fn check_associated_item(
192 sig_if_method: Option<&hir::MethodSig>,
194 debug!("check_associated_item: {:?}", item_id);
196 let code = ObligationCauseCode::MiscObligation;
197 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
198 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
200 let (mut implied_bounds, self_ty) = match item.container {
201 ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
202 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
203 fcx.tcx.type_of(def_id))
207 ty::AssocKind::Const => {
208 let ty = fcx.tcx.type_of(item.def_id);
209 let ty = fcx.normalize_associated_types_in(span, &ty);
210 fcx.register_wf_obligation(ty, span, code.clone());
212 ty::AssocKind::Method => {
213 let sig = fcx.tcx.fn_sig(item.def_id);
214 let sig = fcx.normalize_associated_types_in(span, &sig);
215 check_fn_or_method(tcx, fcx, span, sig,
216 item.def_id, &mut implied_bounds);
217 let sig_if_method = sig_if_method.expect("bad signature for method");
218 check_method_receiver(fcx, sig_if_method, &item, self_ty);
220 ty::AssocKind::Type => {
221 if item.defaultness.has_value() {
222 let ty = fcx.tcx.type_of(item.def_id);
223 let ty = fcx.normalize_associated_types_in(span, &ty);
224 fcx.register_wf_obligation(ty, span, code.clone());
227 ty::AssocKind::OpaqueTy => {
228 // Do nothing: opaque types check themselves.
236 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item) -> CheckWfFcxBuilder<'tcx> {
237 for_id(tcx, item.hir_id, item.span)
240 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
241 let def_id = tcx.hir().local_def_id(id);
243 inherited: Inherited::build(tcx, def_id),
246 param_env: tcx.param_env(def_id),
250 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
251 fn check_type_defn<'tcx, F>(
255 mut lookup_fields: F,
257 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
259 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
260 let variants = lookup_fields(fcx);
261 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
262 let packed = fcx.tcx.adt_def(def_id).repr.packed();
264 for variant in &variants {
265 // For DST, or when drop needs to copy things around, all
266 // intermediate types must be sized.
267 let needs_drop_copy = || {
269 let ty = variant.fields.last().unwrap().ty;
270 let ty = fcx.tcx.erase_regions(&ty);
271 if ty.has_local_value() {
272 fcx_tcx.sess.delay_span_bug(
273 item.span, &format!("inference variables in {:?}", ty));
274 // Just treat unresolved type expression as if it needs drop.
277 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
283 variant.fields.is_empty() ||
285 let unsized_len = if all_sized {
290 for (idx, field) in variant.fields[..variant.fields.len() - unsized_len]
294 let last = idx == variant.fields.len() - 1;
297 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
298 traits::ObligationCause::new(
302 adt_kind: match item.node.adt_kind() {
312 // All field types must be well-formed.
313 for field in &variant.fields {
314 fcx.register_wf_obligation(field.ty, field.span,
315 ObligationCauseCode::MiscObligation)
319 check_where_clauses(tcx, fcx, item.span, def_id, None);
321 // No implied bounds in a struct definition.
326 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item) {
327 debug!("check_trait: {:?}", item.hir_id);
329 let trait_def_id = tcx.hir().local_def_id(item.hir_id);
331 let trait_def = tcx.trait_def(trait_def_id);
332 if trait_def.is_marker {
333 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
336 tcx.def_span(*associated_def_id),
338 "marker traits cannot have associated items",
343 for_item(tcx, item).with_fcx(|fcx, _| {
344 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
349 fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item) {
350 for_item(tcx, item).with_fcx(|fcx, tcx| {
351 let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
352 let sig = fcx.tcx.fn_sig(def_id);
353 let sig = fcx.normalize_associated_types_in(item.span, &sig);
354 let mut implied_bounds = vec![];
355 check_fn_or_method(tcx, fcx, item.span, sig,
356 def_id, &mut implied_bounds);
365 allow_foreign_ty: bool,
367 debug!("check_item_type: {:?}", item_id);
369 for_id(tcx, item_id, ty_span).with_fcx(|fcx, gcx| {
370 let ty = gcx.type_of(gcx.hir().local_def_id(item_id));
371 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
373 let mut forbid_unsized = true;
374 if allow_foreign_ty {
375 let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
376 if let ty::Foreign(_) = tail.kind {
377 forbid_unsized = false;
381 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
385 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
386 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
390 // No implied bounds in a const, etc.
398 ast_self_ty: &hir::Ty,
399 ast_trait_ref: &Option<hir::TraitRef>,
401 debug!("check_impl: {:?}", item);
403 for_item(tcx, item).with_fcx(|fcx, tcx| {
404 let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
406 match *ast_trait_ref {
407 Some(ref ast_trait_ref) => {
408 // `#[rustc_reservation_impl]` impls are not real impls and
409 // therefore don't need to be WF (the trait's `Self: Trait` predicate
411 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
413 fcx.normalize_associated_types_in(
414 ast_trait_ref.path.span, &trait_ref);
416 ty::wf::trait_obligations(fcx,
420 ast_trait_ref.path.span);
421 for obligation in obligations {
422 fcx.register_predicate(obligation);
426 let self_ty = fcx.tcx.type_of(item_def_id);
427 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
428 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
429 ObligationCauseCode::MiscObligation);
433 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
435 fcx.impl_implied_bounds(item_def_id, item.span)
439 /// Checks where-clauses and inline bounds that are declared on `def_id`.
440 fn check_where_clauses<'tcx, 'fcx>(
442 fcx: &FnCtxt<'fcx, 'tcx>,
445 return_ty: Option<Ty<'tcx>>,
447 debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
449 let predicates = fcx.tcx.predicates_of(def_id);
450 let generics = tcx.generics_of(def_id);
452 let is_our_default = |def: &ty::GenericParamDef| {
454 GenericParamDefKind::Type { has_default, .. } => {
455 has_default && def.index >= generics.parent_count as u32
461 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
462 // For example, this forbids the declaration:
464 // struct Foo<T = Vec<[u32]>> { .. }
466 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
467 for param in &generics.params {
468 if let GenericParamDefKind::Type { .. } = param.kind {
469 if is_our_default(¶m) {
470 let ty = fcx.tcx.type_of(param.def_id);
471 // Ignore dependent defaults -- that is, where the default of one type
472 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
473 // be sure if it will error or not as user might always specify the other.
474 if !ty.needs_subst() {
475 fcx.register_wf_obligation(ty, fcx.tcx.def_span(param.def_id),
476 ObligationCauseCode::MiscObligation);
482 // Check that trait predicates are WF when params are substituted by their defaults.
483 // We don't want to overly constrain the predicates that may be written but we want to
484 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
485 // Therefore we check if a predicate which contains a single type param
486 // with a concrete default is WF with that default substituted.
487 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
489 // First we build the defaulted substitution.
490 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
492 GenericParamDefKind::Lifetime => {
493 // All regions are identity.
494 fcx.tcx.mk_param_from_def(param)
497 GenericParamDefKind::Type { .. } => {
498 // If the param has a default, ...
499 if is_our_default(param) {
500 let default_ty = fcx.tcx.type_of(param.def_id);
501 // ... and it's not a dependent default, ...
502 if !default_ty.needs_subst() {
503 // ... then substitute it with the default.
504 return default_ty.into();
507 // Mark unwanted params as error.
508 fcx.tcx.types.err.into()
511 GenericParamDefKind::Const => {
512 // FIXME(const_generics:defaults)
513 fcx.tcx.consts.err.into()
518 // Now we build the substituted predicates.
519 let default_obligations = predicates.predicates.iter().flat_map(|&(pred, sp)| {
521 struct CountParams { params: FxHashSet<u32> }
522 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
523 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
524 if let ty::Param(param) = t.kind {
525 self.params.insert(param.index);
527 t.super_visit_with(self)
530 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
534 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
535 if let ConstValue::Param(param) = c.val {
536 self.params.insert(param.index);
538 c.super_visit_with(self)
541 let mut param_count = CountParams::default();
542 let has_region = pred.visit_with(&mut param_count);
543 let substituted_pred = pred.subst(fcx.tcx, substs);
544 // Don't check non-defaulted params, dependent defaults (including lifetimes)
545 // or preds with multiple params.
546 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
548 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
549 // Avoid duplication of predicates that contain no parameters, for example.
552 Some((substituted_pred, sp))
554 }).map(|(pred, sp)| {
555 // Convert each of those into an obligation. So if you have
556 // something like `struct Foo<T: Copy = String>`, we would
557 // take that predicate `T: Copy`, substitute to `String: Copy`
558 // (actually that happens in the previous `flat_map` call),
559 // and then try to prove it (in this case, we'll fail).
561 // Note the subtle difference from how we handle `predicates`
562 // below: there, we are not trying to prove those predicates
563 // to be *true* but merely *well-formed*.
564 let pred = fcx.normalize_associated_types_in(sp, &pred);
565 let cause = traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
566 traits::Obligation::new(cause, fcx.param_env, pred)
569 let mut predicates = predicates.instantiate_identity(fcx.tcx);
571 if let Some(return_ty) = return_ty {
572 predicates.predicates.extend(check_opaque_types(tcx, fcx, def_id, span, return_ty));
575 let predicates = fcx.normalize_associated_types_in(span, &predicates);
577 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
579 predicates.predicates
581 .flat_map(|p| ty::wf::predicate_obligations(fcx,
587 for obligation in wf_obligations.chain(default_obligations) {
588 debug!("next obligation cause: {:?}", obligation.cause);
589 fcx.register_predicate(obligation);
593 fn check_fn_or_method<'fcx, 'tcx>(
595 fcx: &FnCtxt<'fcx, 'tcx>,
597 sig: ty::PolyFnSig<'tcx>,
599 implied_bounds: &mut Vec<Ty<'tcx>>,
601 let sig = fcx.normalize_associated_types_in(span, &sig);
602 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
604 for input_ty in sig.inputs() {
605 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
607 implied_bounds.extend(sig.inputs());
609 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::ReturnType);
611 // FIXME(#25759) return types should not be implied bounds
612 implied_bounds.push(sig.output());
614 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
617 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
618 /// laid for "higher-order pattern unification".
619 /// This ensures that inference is tractable.
620 /// In particular, definitions of opaque types can only use other generics as arguments,
621 /// and they cannot repeat an argument. Example:
624 /// type Foo<A, B> = impl Bar<A, B>;
626 /// // Okay -- `Foo` is applied to two distinct, generic types.
627 /// fn a<T, U>() -> Foo<T, U> { .. }
629 /// // Not okay -- `Foo` is applied to `T` twice.
630 /// fn b<T>() -> Foo<T, T> { .. }
632 /// // Not okay -- `Foo` is applied to a non-generic type.
633 /// fn b<T>() -> Foo<T, u32> { .. }
636 fn check_opaque_types<'fcx, 'tcx>(
638 fcx: &FnCtxt<'fcx, 'tcx>,
642 ) -> Vec<ty::Predicate<'tcx>> {
643 trace!("check_opaque_types(ty={:?})", ty);
644 let mut substituted_predicates = Vec::new();
645 ty.fold_with(&mut ty::fold::BottomUpFolder {
648 if let ty::Opaque(def_id, substs) = ty.kind {
649 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
650 let generics = tcx.generics_of(def_id);
651 // Only check named `impl Trait` types defined in this crate.
652 if generics.parent.is_none() && def_id.is_local() {
653 let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
654 if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
655 trace!("check_opaque_types: may define, generics={:#?}", generics);
656 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
657 for (subst, param) in substs.iter().zip(&generics.params) {
658 match subst.unpack() {
659 ty::subst::GenericArgKind::Type(ty) => match ty.kind {
661 // Prevent `fn foo() -> Foo<u32>` from being defining.
666 "non-defining opaque type use \
670 tcx.def_span(param.def_id),
672 "used non-generic type {} for \
681 ty::subst::GenericArgKind::Lifetime(region) => {
682 let param_span = tcx.def_span(param.def_id);
683 if let ty::ReStatic = region {
688 "non-defining opaque type use \
693 "cannot use static lifetime; use a bound lifetime \
694 instead or remove the lifetime parameter from the \
699 seen.entry(region).or_default().push(param_span);
703 ty::subst::GenericArgKind::Const(ct) => match ct.val {
704 ConstValue::Param(_) => {}
709 "non-defining opaque type use \
713 tcx.def_span(param.def_id),
715 "used non-generic const {} for \
724 } // for (subst, param)
725 for (_, spans) in seen {
731 "non-defining opaque type use \
736 "lifetime used multiple times",
741 } // if may_define_opaque_type
743 // Now register the bounds on the parameters of the opaque type
744 // so the parameters given by the function need to fulfill them.
746 // type Foo<T: Bar> = impl Baz + 'static;
747 // fn foo<U>() -> Foo<U> { .. *}
751 // type Foo<T: Bar> = impl Baz + 'static;
752 // fn foo<U: Bar>() -> Foo<U> { .. *}
753 let predicates = tcx.predicates_of(def_id);
755 "check_opaque_types: may define, predicates={:#?}",
758 for &(pred, _) in predicates.predicates.iter() {
759 let substituted_pred = pred.subst(fcx.tcx, substs);
760 // Avoid duplication of predicates that contain no parameters, for example.
761 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
762 substituted_predicates.push(substituted_pred);
765 } // if is_named_opaque_type
772 substituted_predicates
775 const HELP_FOR_SELF_TYPE: &str =
776 "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
777 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
778 of the previous types except `Self`)";
780 fn check_method_receiver<'fcx, 'tcx>(
781 fcx: &FnCtxt<'fcx, 'tcx>,
782 method_sig: &hir::MethodSig,
783 method: &ty::AssocItem,
786 // Check that the method has a valid receiver type, given the type `Self`.
787 debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
789 if !method.method_has_self_argument {
793 let span = method_sig.decl.inputs[0].span;
795 let sig = fcx.tcx.fn_sig(method.def_id);
796 let sig = fcx.normalize_associated_types_in(span, &sig);
797 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
799 debug!("check_method_receiver: sig={:?}", sig);
801 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
802 let self_ty = fcx.tcx.liberate_late_bound_regions(
804 &ty::Binder::bind(self_ty)
807 let receiver_ty = sig.inputs()[0];
809 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
810 let receiver_ty = fcx.tcx.liberate_late_bound_regions(
812 &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,
830 "`{}` cannot be used as the type of `self` without \
831 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<'_>) {
845 fcx.tcx.sess.diagnostic().struct_span_err(
847 &format!("invalid `self` parameter type: {:?}", receiver_ty)
848 ).note("type of `self` must be `Self` or a type that dereferences to it")
849 .help(HELP_FOR_SELF_TYPE)
850 .code(DiagnosticId::Error("E0307".into()))
854 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
855 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
856 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
857 /// strict: `receiver_ty` must implement `Receiver` and directly implement
858 /// `Deref<Target = self_ty>`.
860 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
861 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
862 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
863 fn receiver_is_valid<'fcx, 'tcx>(
864 fcx: &FnCtxt<'fcx, 'tcx>,
866 receiver_ty: Ty<'tcx>,
868 arbitrary_self_types_enabled: bool,
870 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
872 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
874 // `self: Self` is always valid.
875 if can_eq_self(receiver_ty) {
876 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
882 let mut autoderef = fcx.autoderef(span, receiver_ty);
884 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
885 if arbitrary_self_types_enabled {
886 autoderef = autoderef.include_raw_pointers();
889 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
892 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
894 if let Some((potential_self_ty, _)) = autoderef.next() {
895 debug!("receiver_is_valid: potential self type `{:?}` to match `{:?}`",
896 potential_self_ty, self_ty);
898 if can_eq_self(potential_self_ty) {
899 autoderef.finalize(fcx);
901 if let Some(mut err) = fcx.demand_eqtype_with_origin(
902 &cause, self_ty, potential_self_ty
910 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`",
911 receiver_ty, self_ty);
912 // If he receiver already has errors reported due to it, consider it valid to avoid
913 // unecessary errors (#58712).
914 return receiver_ty.references_error();
917 // Without the `arbitrary_self_types` feature, `receiver_ty` must directly deref to
918 // `self_ty`. Enforce this by only doing one iteration of the loop.
919 if !arbitrary_self_types_enabled {
924 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
925 if !arbitrary_self_types_enabled {
926 let trait_def_id = match fcx.tcx.lang_items().receiver_trait() {
929 debug!("receiver_is_valid: missing Receiver trait");
934 let trait_ref = ty::TraitRef{
935 def_id: trait_def_id,
936 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
939 let obligation = traits::Obligation::new(
942 trait_ref.to_predicate()
945 if !fcx.predicate_must_hold_modulo_regions(&obligation) {
946 debug!("receiver_is_valid: type `{:?}` does not implement `Receiver` trait",
955 fn check_variances_for_type_defn<'tcx>(
958 hir_generics: &hir::Generics,
960 let item_def_id = tcx.hir().local_def_id(item.hir_id);
961 let ty = tcx.type_of(item_def_id);
962 if tcx.has_error_field(ty) {
966 let ty_predicates = tcx.predicates_of(item_def_id);
967 assert_eq!(ty_predicates.parent, None);
968 let variances = tcx.variances_of(item_def_id);
970 let mut constrained_parameters: FxHashSet<_> =
971 variances.iter().enumerate()
972 .filter(|&(_, &variance)| variance != ty::Bivariant)
973 .map(|(index, _)| Parameter(index as u32))
976 identify_constrained_generic_params(
980 &mut constrained_parameters,
983 for (index, _) in variances.iter().enumerate() {
984 if constrained_parameters.contains(&Parameter(index as u32)) {
988 let param = &hir_generics.params[index];
991 hir::ParamName::Error => { }
992 _ => report_bivariance(tcx, param.span, param.name.ident().name),
997 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) {
998 let mut err = error_392(tcx, span, param_name);
1000 let suggested_marker_id = tcx.lang_items().phantom_data();
1001 // Help is available only in presence of lang items.
1002 if let Some(def_id) = suggested_marker_id {
1003 err.help(&format!("consider removing `{}` or using a marker such as `{}`",
1005 tcx.def_path_str(def_id)));
1010 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1012 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1013 let empty_env = ty::ParamEnv::empty();
1015 let def_id = fcx.tcx.hir().local_def_id(id);
1016 let predicates = fcx.tcx.predicates_of(def_id).predicates
1020 // Check elaborated bounds.
1021 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1023 for pred in implied_obligations {
1024 // Match the existing behavior.
1025 if pred.is_global() && !pred.has_late_bound_regions() {
1026 let pred = fcx.normalize_associated_types_in(span, &pred);
1027 let obligation = traits::Obligation::new(
1028 traits::ObligationCause::new(
1031 traits::TrivialBound,
1036 fcx.register_predicate(obligation);
1040 fcx.select_all_obligations_or_error();
1043 pub struct CheckTypeWellFormedVisitor<'tcx> {
1047 impl CheckTypeWellFormedVisitor<'tcx> {
1048 pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1049 CheckTypeWellFormedVisitor {
1055 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1056 fn visit_item(&self, i: &'tcx hir::Item) {
1057 debug!("visit_item: {:?}", i);
1058 let def_id = self.tcx.hir().local_def_id(i.hir_id);
1059 self.tcx.ensure().check_item_well_formed(def_id);
1062 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem) {
1063 debug!("visit_trait_item: {:?}", trait_item);
1064 let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1065 self.tcx.ensure().check_trait_item_well_formed(def_id);
1068 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem) {
1069 debug!("visit_impl_item: {:?}", impl_item);
1070 let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1071 self.tcx.ensure().check_impl_item_well_formed(def_id);
1075 ///////////////////////////////////////////////////////////////////////////
1078 struct AdtVariant<'tcx> {
1079 fields: Vec<AdtField<'tcx>>,
1082 struct AdtField<'tcx> {
1087 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1088 fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
1089 let fields = struct_def.fields().iter().map(|field| {
1090 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1091 let field_ty = self.normalize_associated_types_in(field.span,
1093 let field_ty = self.resolve_vars_if_possible(&field_ty);
1094 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1095 AdtField { ty: field_ty, span: field.span }
1098 AdtVariant { fields }
1101 fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
1102 enum_def.variants.iter()
1103 .map(|variant| self.non_enum_variant(&variant.data))
1107 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1108 match self.tcx.impl_trait_ref(impl_def_id) {
1109 Some(ref trait_ref) => {
1110 // Trait impl: take implied bounds from all types that
1111 // appear in the trait reference.
1112 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1113 trait_ref.substs.types().collect()
1117 // Inherent impl: take implied bounds from the `self` type.
1118 let self_ty = self.tcx.type_of(impl_def_id);
1119 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1129 param_name: ast::Name,
1130 ) -> DiagnosticBuilder<'_> {
1131 let mut err = struct_span_err!(tcx.sess, span, E0392,
1132 "parameter `{}` is never used", param_name);
1133 err.span_label(span, "unused parameter");