1 use crate::check::{Inherited, FnCtxt};
2 use crate::constrained_type_params::{identify_constrained_type_params, Parameter};
4 use crate::hir::def_id::DefId;
5 use rustc::traits::{self, ObligationCauseCode};
6 use rustc::ty::{self, Lift, Ty, TyCtxt, TyKind, GenericParamDefKind, TypeFoldable, ToPredicate};
7 use rustc::ty::subst::{Subst, InternalSubsts};
8 use rustc::util::nodemap::{FxHashSet, FxHashMap};
9 use rustc::middle::lang_items;
10 use rustc::infer::opaque_types::may_define_existential_type;
13 use syntax::feature_gate::{self, GateIssue};
15 use errors::{DiagnosticBuilder, DiagnosticId};
17 use rustc::hir::itemlikevisit::ItemLikeVisitor;
20 /// Helper type of a temporary returned by `.for_item(...)`.
21 /// Necessary because we can't write the following bound:
22 /// `F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>)`.
23 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
24 inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
27 param_env: ty::ParamEnv<'tcx>,
30 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
31 fn with_fcx<F>(&'tcx mut self, f: F) where
32 F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
33 TyCtxt<'b, 'gcx, 'gcx>) -> Vec<Ty<'tcx>>
37 let param_env = self.param_env;
38 self.inherited.enter(|inh| {
39 let fcx = FnCtxt::new(&inh, param_env, id);
40 if !inh.tcx.features().trivial_bounds {
41 // As predicates are cached rather than obligations, this
42 // needsto be called first so that they are checked with an
44 check_false_global_bounds(&fcx, span, id);
46 let wf_tys = f(&fcx, fcx.tcx.global_tcx());
47 fcx.select_all_obligations_or_error();
48 fcx.regionck_item(id, span, &wf_tys);
53 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
54 /// well-formed, meaning that they do not require any constraints not declared in the struct
55 /// definition itself. For example, this definition would be illegal:
57 /// struct Ref<'a, T> { x: &'a T }
59 /// because the type did not declare that `T:'a`.
61 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
62 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
64 pub fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
65 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
66 let item = tcx.hir().expect_item_by_hir_id(hir_id);
68 debug!("check_item_well_formed(it.hir_id={:?}, it.name={})",
70 tcx.item_path_str(def_id));
73 // Right now we check that every default trait implementation
74 // has an implementation of itself. Basically, a case like:
76 // `impl Trait for T {}`
78 // has a requirement of `T: Trait` which was required for default
79 // method implementations. Although this could be improved now that
80 // there's a better infrastructure in place for this, it's being left
81 // for a follow-up work.
83 // Since there's such a requirement, we need to check *just* positive
84 // implementations, otherwise things like:
86 // impl !Send for T {}
88 // won't be allowed unless there's an *explicit* implementation of `Send`
90 hir::ItemKind::Impl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
91 let is_auto = tcx.impl_trait_ref(tcx.hir().local_def_id_from_hir_id(item.hir_id))
92 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
93 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
94 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
96 if polarity == hir::ImplPolarity::Positive {
97 check_impl(tcx, item, self_ty, trait_ref);
99 // FIXME(#27579) what amount of WF checking do we need for neg impls?
100 if trait_ref.is_some() && !is_auto {
101 span_err!(tcx.sess, item.span, E0192,
102 "negative impls are only allowed for \
103 auto traits (e.g., `Send` and `Sync`)")
107 hir::ItemKind::Fn(..) => {
108 check_item_fn(tcx, item);
110 hir::ItemKind::Static(ref ty, ..) => {
111 check_item_type(tcx, item.hir_id, ty.span, false);
113 hir::ItemKind::Const(ref ty, ..) => {
114 check_item_type(tcx, item.hir_id, ty.span, false);
116 hir::ItemKind::ForeignMod(ref module) => for it in module.items.iter() {
117 if let hir::ForeignItemKind::Static(ref ty, ..) = it.node {
118 check_item_type(tcx, it.hir_id, ty.span, true);
121 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
122 check_type_defn(tcx, item, false, |fcx| {
123 vec![fcx.non_enum_variant(struct_def)]
126 check_variances_for_type_defn(tcx, item, ast_generics);
128 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
129 check_type_defn(tcx, item, true, |fcx| {
130 vec![fcx.non_enum_variant(struct_def)]
133 check_variances_for_type_defn(tcx, item, ast_generics);
135 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
136 check_type_defn(tcx, item, true, |fcx| {
137 fcx.enum_variants(enum_def)
140 check_variances_for_type_defn(tcx, item, ast_generics);
142 hir::ItemKind::Trait(..) => {
143 check_trait(tcx, item);
145 hir::ItemKind::TraitAlias(..) => {
146 check_trait(tcx, item);
152 pub fn check_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
153 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
154 let trait_item = tcx.hir().expect_trait_item(node_id);
156 let method_sig = match trait_item.node {
157 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
160 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
163 pub fn check_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
164 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
165 let impl_item = tcx.hir().expect_impl_item(node_id);
167 let method_sig = match impl_item.node {
168 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
171 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
174 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
177 sig_if_method: Option<&hir::MethodSig>) {
178 debug!("check_associated_item: {:?}", item_id);
180 let code = ObligationCauseCode::MiscObligation;
181 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
182 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id_from_hir_id(item_id));
184 let (mut implied_bounds, self_ty) = match item.container {
185 ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
186 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
187 fcx.tcx.type_of(def_id))
191 ty::AssociatedKind::Const => {
192 let ty = fcx.tcx.type_of(item.def_id);
193 let ty = fcx.normalize_associated_types_in(span, &ty);
194 fcx.register_wf_obligation(ty, span, code.clone());
196 ty::AssociatedKind::Method => {
197 reject_shadowing_parameters(fcx.tcx, item.def_id);
198 let sig = fcx.tcx.fn_sig(item.def_id);
199 let sig = fcx.normalize_associated_types_in(span, &sig);
200 check_fn_or_method(tcx, fcx, span, sig,
201 item.def_id, &mut implied_bounds);
202 let sig_if_method = sig_if_method.expect("bad signature for method");
203 check_method_receiver(fcx, sig_if_method, &item, self_ty);
205 ty::AssociatedKind::Type => {
206 if item.defaultness.has_value() {
207 let ty = fcx.tcx.type_of(item.def_id);
208 let ty = fcx.normalize_associated_types_in(span, &ty);
209 fcx.register_wf_obligation(ty, span, code.clone());
212 ty::AssociatedKind::Existential => {
213 // do nothing, existential types check themselves
221 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
222 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
223 for_id(tcx, item.hir_id, item.span)
226 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: hir::HirId, span: Span)
227 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
228 let def_id = tcx.hir().local_def_id_from_hir_id(id);
230 inherited: Inherited::build(tcx, def_id),
233 param_env: tcx.param_env(def_id),
237 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
238 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
239 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
240 where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
242 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
243 let variants = lookup_fields(fcx);
244 let def_id = fcx.tcx.hir().local_def_id(item.id);
245 let packed = fcx.tcx.adt_def(def_id).repr.packed();
247 for variant in &variants {
248 // For DST, or when drop needs to copy things around, all
249 // intermediate types must be sized.
250 let needs_drop_copy = || {
252 let ty = variant.fields.last().unwrap().ty;
253 let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
255 span_bug!(item.span, "inference variables in {:?}", ty)
257 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
262 variant.fields.is_empty() ||
264 let unsized_len = if all_sized {
269 for (idx, field) in variant.fields[..variant.fields.len() - unsized_len]
273 let last = idx == variant.fields.len() - 1;
276 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
277 traits::ObligationCause::new(
281 adt_kind: match item.node.adt_kind() {
291 // All field types must be well-formed.
292 for field in &variant.fields {
293 fcx.register_wf_obligation(field.ty, field.span,
294 ObligationCauseCode::MiscObligation)
298 check_where_clauses(tcx, fcx, item.span, def_id, None);
300 vec![] // no implied bounds in a struct def'n
304 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
305 debug!("check_trait: {:?}", item.id);
307 let trait_def_id = tcx.hir().local_def_id(item.id);
309 let trait_def = tcx.trait_def(trait_def_id);
310 if trait_def.is_marker {
311 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
314 tcx.def_span(*associated_def_id),
316 "marker traits cannot have associated items",
321 for_item(tcx, item).with_fcx(|fcx, _| {
322 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
327 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
328 for_item(tcx, item).with_fcx(|fcx, tcx| {
329 let def_id = fcx.tcx.hir().local_def_id(item.id);
330 let sig = fcx.tcx.fn_sig(def_id);
331 let sig = fcx.normalize_associated_types_in(item.span, &sig);
332 let mut implied_bounds = vec![];
333 check_fn_or_method(tcx, fcx, item.span, sig,
334 def_id, &mut implied_bounds);
339 fn check_item_type<'a, 'tcx>(
340 tcx: TyCtxt<'a, 'tcx, 'tcx>,
343 allow_foreign_ty: bool,
345 debug!("check_item_type: {:?}", item_id);
347 for_id(tcx, item_id, ty_span).with_fcx(|fcx, gcx| {
348 let ty = gcx.type_of(gcx.hir().local_def_id_from_hir_id(item_id));
349 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
351 let mut forbid_unsized = true;
352 if allow_foreign_ty {
353 if let TyKind::Foreign(_) = fcx.tcx.struct_tail(item_ty).sty {
354 forbid_unsized = false;
358 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
362 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
363 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
367 vec![] // no implied bounds in a const etc
371 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
373 ast_self_ty: &hir::Ty,
374 ast_trait_ref: &Option<hir::TraitRef>)
376 debug!("check_impl: {:?}", item);
378 for_item(tcx, item).with_fcx(|fcx, tcx| {
379 let item_def_id = fcx.tcx.hir().local_def_id(item.id);
381 match *ast_trait_ref {
382 Some(ref ast_trait_ref) => {
383 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
385 fcx.normalize_associated_types_in(
386 ast_trait_ref.path.span, &trait_ref);
388 ty::wf::trait_obligations(fcx,
392 ast_trait_ref.path.span);
393 for obligation in obligations {
394 fcx.register_predicate(obligation);
398 let self_ty = fcx.tcx.type_of(item_def_id);
399 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
400 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
401 ObligationCauseCode::MiscObligation);
405 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
407 fcx.impl_implied_bounds(item_def_id, item.span)
411 /// Checks where-clauses and inline bounds that are declared on `def_id`.
412 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
413 tcx: TyCtxt<'a, 'gcx, 'gcx>,
414 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
417 return_ty: Option<Ty<'tcx>>,
419 use ty::subst::Subst;
420 use rustc::ty::TypeFoldable;
422 let predicates = fcx.tcx.predicates_of(def_id);
424 let generics = tcx.generics_of(def_id);
425 let is_our_default = |def: &ty::GenericParamDef| {
427 GenericParamDefKind::Type { has_default, .. } => {
428 has_default && def.index >= generics.parent_count as u32
434 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
435 // For example this forbids the declaration:
436 // struct Foo<T = Vec<[u32]>> { .. }
437 // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
438 for param in &generics.params {
439 if let GenericParamDefKind::Type {..} = param.kind {
440 if is_our_default(¶m) {
441 let ty = fcx.tcx.type_of(param.def_id);
442 // ignore dependent defaults -- that is, where the default of one type
443 // parameter includes another (e.g., <T, U = T>). In those cases, we can't
444 // be sure if it will error or not as user might always specify the other.
445 if !ty.needs_subst() {
446 fcx.register_wf_obligation(ty, fcx.tcx.def_span(param.def_id),
447 ObligationCauseCode::MiscObligation);
453 // Check that trait predicates are WF when params are substituted by their defaults.
454 // We don't want to overly constrain the predicates that may be written but we want to
455 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
456 // Therefore we check if a predicate which contains a single type param
457 // with a concrete default is WF with that default substituted.
458 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
460 // First we build the defaulted substitution.
461 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
463 GenericParamDefKind::Lifetime => {
464 // All regions are identity.
465 fcx.tcx.mk_param_from_def(param)
467 GenericParamDefKind::Type {..} => {
468 // If the param has a default,
469 if is_our_default(param) {
470 let default_ty = fcx.tcx.type_of(param.def_id);
471 // and it's not a dependent default
472 if !default_ty.needs_subst() {
473 // then substitute with the default.
474 return default_ty.into();
477 // Mark unwanted params as err.
478 fcx.tcx.types.err.into()
482 // Now we build the substituted predicates.
483 let default_obligations = predicates.predicates.iter().flat_map(|&(pred, _)| {
485 struct CountParams { params: FxHashSet<u32> }
486 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
487 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
490 self.params.insert(p.idx);
491 t.super_visit_with(self)
493 _ => t.super_visit_with(self)
497 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
501 let mut param_count = CountParams::default();
502 let has_region = pred.visit_with(&mut param_count);
503 let substituted_pred = pred.subst(fcx.tcx, substs);
504 // Don't check non-defaulted params, dependent defaults (including lifetimes)
505 // or preds with multiple params.
506 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
508 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
509 // Avoid duplication of predicates that contain no parameters, for example.
512 Some(substituted_pred)
515 // convert each of those into an obligation. So if you have
516 // something like `struct Foo<T: Copy = String>`, we would
517 // take that predicate `T: Copy`, substitute to `String: Copy`
518 // (actually that happens in the previous `flat_map` call),
519 // and then try to prove it (in this case, we'll fail).
521 // Note the subtle difference from how we handle `predicates`
522 // below: there, we are not trying to prove those predicates
523 // to be *true* but merely *well-formed*.
524 let pred = fcx.normalize_associated_types_in(span, &pred);
525 let cause = traits::ObligationCause::new(span, fcx.body_id, traits::ItemObligation(def_id));
526 traits::Obligation::new(cause, fcx.param_env, pred)
529 let mut predicates = predicates.instantiate_identity(fcx.tcx);
531 if let Some(return_ty) = return_ty {
532 predicates.predicates.extend(check_existential_types(tcx, fcx, def_id, span, return_ty));
535 let predicates = fcx.normalize_associated_types_in(span, &predicates);
537 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
539 predicates.predicates
541 .flat_map(|p| ty::wf::predicate_obligations(fcx,
547 for obligation in wf_obligations.chain(default_obligations) {
548 debug!("next obligation cause: {:?}", obligation.cause);
549 fcx.register_predicate(obligation);
553 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
554 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
556 sig: ty::PolyFnSig<'tcx>,
558 implied_bounds: &mut Vec<Ty<'tcx>>)
560 let sig = fcx.normalize_associated_types_in(span, &sig);
561 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
563 for input_ty in sig.inputs() {
564 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
566 implied_bounds.extend(sig.inputs());
568 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
570 // FIXME(#25759) return types should not be implied bounds
571 implied_bounds.push(sig.output());
573 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
576 /// Checks "defining uses" of existential types to ensure that they meet the restrictions laid for
577 /// "higher-order pattern unification".
578 /// This ensures that inference is tractable.
579 /// In particular, definitions of existential types can only use other generics as arguments,
580 /// and they cannot repeat an argument. Example:
583 /// existential type Foo<A, B>;
585 /// // ok -- `Foo` is applied to two distinct, generic types.
586 /// fn a<T, U>() -> Foo<T, U> { .. }
588 /// // not ok -- `Foo` is applied to `T` twice.
589 /// fn b<T>() -> Foo<T, T> { .. }
592 /// // not ok -- `Foo` is applied to a non-generic type.
593 /// fn b<T>() -> Foo<T, u32> { .. }
596 fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>(
597 tcx: TyCtxt<'a, 'gcx, 'gcx>,
598 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
602 ) -> Vec<ty::Predicate<'tcx>> {
603 trace!("check_existential_types: {:?}, {:?}", ty, ty.sty);
604 let mut substituted_predicates = Vec::new();
605 ty.fold_with(&mut ty::fold::BottomUpFolder {
608 if let ty::Opaque(def_id, substs) = ty.sty {
609 trace!("check_existential_types: opaque_ty, {:?}, {:?}", def_id, substs);
610 let generics = tcx.generics_of(def_id);
611 // only check named existential types defined in this crate
612 if generics.parent.is_none() && def_id.is_local() {
613 let opaque_node_id = tcx.hir().as_local_node_id(def_id).unwrap();
614 if may_define_existential_type(tcx, fn_def_id, opaque_node_id) {
615 trace!("check_existential_types may define. Generics: {:#?}", generics);
616 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
617 for (subst, param) in substs.iter().zip(&generics.params) {
618 match subst.unpack() {
619 ty::subst::UnpackedKind::Type(ty) => match ty.sty {
621 // prevent `fn foo() -> Foo<u32>` from being defining
627 "non-defining existential type use \
631 tcx.def_span(param.def_id),
633 "used non-generic type {} for \
641 ty::subst::UnpackedKind::Lifetime(region) => {
642 let param_span = tcx.def_span(param.def_id);
643 if let ty::ReStatic = region {
648 "non-defining existential type use \
653 "cannot use static lifetime, use a bound lifetime \
654 instead or remove the lifetime parameter from the \
659 seen.entry(region).or_default().push(param_span);
663 } // for (subst, param)
664 for (_, spans) in seen {
670 "non-defining existential type use \
675 "lifetime used multiple times",
680 } // if may_define_existential_type
682 // now register the bounds on the parameters of the existential type
683 // so the parameters given by the function need to fulfill them
685 // existential type Foo<T: Bar>: 'static;
686 // fn foo<U>() -> Foo<U> { .. *}
690 // existential type Foo<T: Bar>: 'static;
691 // fn foo<U: Bar>() -> Foo<U> { .. *}
693 let predicates = tcx.predicates_of(def_id);
695 "check_existential_types may define. adding predicates: {:#?}",
698 for &(pred, _) in predicates.predicates.iter() {
699 let substituted_pred = pred.subst(fcx.tcx, substs);
700 // Avoid duplication of predicates that contain no parameters, for example.
701 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
702 substituted_predicates.push(substituted_pred);
705 } // if is_named_existential_type
711 substituted_predicates
714 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
715 method_sig: &hir::MethodSig,
716 method: &ty::AssociatedItem,
719 // check that the method has a valid receiver type, given the type `Self`
720 debug!("check_method_receiver({:?}, self_ty={:?})",
723 if !method.method_has_self_argument {
727 let span = method_sig.decl.inputs[0].span;
729 let sig = fcx.tcx.fn_sig(method.def_id);
730 let sig = fcx.normalize_associated_types_in(span, &sig);
731 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
733 debug!("check_method_receiver: sig={:?}", sig);
735 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
736 let self_ty = fcx.tcx.liberate_late_bound_regions(
738 &ty::Binder::bind(self_ty)
741 let receiver_ty = sig.inputs()[0];
743 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
744 let receiver_ty = fcx.tcx.liberate_late_bound_regions(
746 &ty::Binder::bind(receiver_ty)
749 if fcx.tcx.features().arbitrary_self_types {
750 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
751 // report error, arbitrary_self_types was enabled
752 fcx.tcx.sess.diagnostic().mut_span_err(
753 span, &format!("invalid method receiver type: {:?}", receiver_ty)
754 ).note("type of `self` must be `Self` or a type that dereferences to it")
755 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
756 .code(DiagnosticId::Error("E0307".into()))
760 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
761 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
762 // report error, would have worked with arbitrary_self_types
763 feature_gate::feature_err(
764 &fcx.tcx.sess.parse_sess,
765 "arbitrary_self_types",
769 "`{}` cannot be used as the type of `self` without \
770 the `arbitrary_self_types` feature",
773 ).help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
776 // report error, would not have worked with arbitrary_self_types
777 fcx.tcx.sess.diagnostic().mut_span_err(
778 span, &format!("invalid method receiver type: {:?}", receiver_ty)
779 ).note("type must be `Self` or a type that dereferences to it")
780 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
781 .code(DiagnosticId::Error("E0307".into()))
788 /// returns true if `receiver_ty` would be considered a valid receiver type for `self_ty`. If
789 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
790 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
791 /// strict: `receiver_ty` must implement `Receiver` and directly implement `Deref<Target=self_ty>`.
793 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
794 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
795 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
796 fn receiver_is_valid<'fcx, 'tcx, 'gcx>(
797 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
799 receiver_ty: Ty<'tcx>,
801 arbitrary_self_types_enabled: bool,
803 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
805 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
807 // `self: Self` is always valid
808 if can_eq_self(receiver_ty) {
809 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
815 let mut autoderef = fcx.autoderef(span, receiver_ty);
817 // the `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`
818 if arbitrary_self_types_enabled {
819 autoderef = autoderef.include_raw_pointers();
822 // the first type is `receiver_ty`, which we know its not equal to `self_ty`. skip it.
825 // keep dereferencing `receiver_ty` until we get to `self_ty`
827 if let Some((potential_self_ty, _)) = autoderef.next() {
828 debug!("receiver_is_valid: potential self type `{:?}` to match `{:?}`",
829 potential_self_ty, self_ty);
831 if can_eq_self(potential_self_ty) {
832 autoderef.finalize(fcx);
834 if let Some(mut err) = fcx.demand_eqtype_with_origin(
835 &cause, self_ty, potential_self_ty
843 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`",
844 receiver_ty, self_ty);
848 // without the `arbitrary_self_types` feature, `receiver_ty` must directly deref to
849 // `self_ty`. Enforce this by only doing one iteration of the loop
850 if !arbitrary_self_types_enabled {
855 // without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`
856 if !arbitrary_self_types_enabled {
857 let trait_def_id = match fcx.tcx.lang_items().receiver_trait() {
860 debug!("receiver_is_valid: missing Receiver trait");
865 let trait_ref = ty::TraitRef{
866 def_id: trait_def_id,
867 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
870 let obligation = traits::Obligation::new(
873 trait_ref.to_predicate()
876 if !fcx.predicate_must_hold_modulo_regions(&obligation) {
877 debug!("receiver_is_valid: type `{:?}` does not implement `Receiver` trait",
886 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
888 hir_generics: &hir::Generics)
890 let item_def_id = tcx.hir().local_def_id(item.id);
891 let ty = tcx.type_of(item_def_id);
892 if tcx.has_error_field(ty) {
896 let ty_predicates = tcx.predicates_of(item_def_id);
897 assert_eq!(ty_predicates.parent, None);
898 let variances = tcx.variances_of(item_def_id);
900 let mut constrained_parameters: FxHashSet<_> =
901 variances.iter().enumerate()
902 .filter(|&(_, &variance)| variance != ty::Bivariant)
903 .map(|(index, _)| Parameter(index as u32))
906 identify_constrained_type_params(tcx,
909 &mut constrained_parameters);
911 for (index, _) in variances.iter().enumerate() {
912 if constrained_parameters.contains(&Parameter(index as u32)) {
916 let param = &hir_generics.params[index];
918 hir::ParamName::Error => { }
919 _ => report_bivariance(tcx, param.span, param.name.ident().name),
924 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
926 param_name: ast::Name)
928 let mut err = error_392(tcx, span, param_name);
930 let suggested_marker_id = tcx.lang_items().phantom_data();
931 // help is available only in presence of lang items
932 if let Some(def_id) = suggested_marker_id {
933 err.help(&format!("consider removing `{}` or using a marker such as `{}`",
935 tcx.item_path_str(def_id)));
940 fn reject_shadowing_parameters(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) {
941 let generics = tcx.generics_of(def_id);
942 let parent = tcx.generics_of(generics.parent.unwrap());
943 let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
944 GenericParamDefKind::Lifetime => None,
945 GenericParamDefKind::Type {..} => Some((param.name, param.def_id)),
948 for method_param in &generics.params {
949 // Shadowing is checked in resolve_lifetime.
950 if let GenericParamDefKind::Lifetime = method_param.kind {
953 if impl_params.contains_key(&method_param.name) {
954 // Tighten up the span to focus on only the shadowing type
955 let type_span = tcx.def_span(method_param.def_id);
957 // The expectation here is that the original trait declaration is
958 // local so it should be okay to just unwrap everything.
959 let trait_def_id = impl_params[&method_param.name];
960 let trait_decl_span = tcx.def_span(trait_def_id);
961 error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
966 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
968 fn check_false_global_bounds<'a, 'gcx, 'tcx>(
969 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
973 use rustc::ty::TypeFoldable;
975 let empty_env = ty::ParamEnv::empty();
977 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(id);
978 let predicates = fcx.tcx.predicates_of(def_id).predicates
982 // Check elaborated bounds
983 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
985 for pred in implied_obligations {
986 // Match the existing behavior.
987 if pred.is_global() && !pred.has_late_bound_regions() {
988 let pred = fcx.normalize_associated_types_in(span, &pred);
989 let obligation = traits::Obligation::new(
990 traits::ObligationCause::new(
993 traits::TrivialBound,
998 fcx.register_predicate(obligation);
1002 fcx.select_all_obligations_or_error();
1005 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
1006 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1009 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
1010 pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
1011 -> CheckTypeWellFormedVisitor<'a, 'gcx> {
1012 CheckTypeWellFormedVisitor {
1018 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'a, 'tcx> {
1019 fn visit_item(&mut self, i: &'tcx hir::Item) {
1020 debug!("visit_item: {:?}", i);
1021 let def_id = self.tcx.hir().local_def_id(i.id);
1022 self.tcx.ensure().check_item_well_formed(def_id);
1025 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
1026 debug!("visit_trait_item: {:?}", trait_item);
1027 let def_id = self.tcx.hir().local_def_id_from_hir_id(trait_item.hir_id);
1028 self.tcx.ensure().check_trait_item_well_formed(def_id);
1031 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
1032 debug!("visit_impl_item: {:?}", impl_item);
1033 let def_id = self.tcx.hir().local_def_id(impl_item.id);
1034 self.tcx.ensure().check_impl_item_well_formed(def_id);
1038 ///////////////////////////////////////////////////////////////////////////
1041 struct AdtVariant<'tcx> {
1042 fields: Vec<AdtField<'tcx>>,
1045 struct AdtField<'tcx> {
1050 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1051 fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
1052 let fields = struct_def.fields().iter().map(|field| {
1053 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.id));
1054 let field_ty = self.normalize_associated_types_in(field.span,
1056 AdtField { ty: field_ty, span: field.span }
1059 AdtVariant { fields }
1062 fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
1063 enum_def.variants.iter()
1064 .map(|variant| self.non_enum_variant(&variant.node.data))
1068 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1069 match self.tcx.impl_trait_ref(impl_def_id) {
1070 Some(ref trait_ref) => {
1071 // Trait impl: take implied bounds from all types that
1072 // appear in the trait reference.
1073 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1074 trait_ref.substs.types().collect()
1078 // Inherent impl: take implied bounds from the `self` type.
1079 let self_ty = self.tcx.type_of(impl_def_id);
1080 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1087 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
1088 -> DiagnosticBuilder<'tcx> {
1089 let mut err = struct_span_err!(tcx.sess, span, E0392,
1090 "parameter `{}` is never used", param_name);
1091 err.span_label(span, "unused type parameter");
1095 fn error_194(tcx: TyCtxt<'_, '_, '_>, span: Span, trait_decl_span: Span, name: &str) {
1096 struct_span_err!(tcx.sess, span, E0194,
1097 "type parameter `{}` shadows another type parameter of the same name",
1099 .span_label(span, "shadows another type parameter")
1100 .span_label(trait_decl_span, format!("first `{}` declared here", name))