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, Lift, 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_existential_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 /// Necessary because we can't write the following bound:
24 /// `F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>)`.
25 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
26 inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
29 param_env: ty::ParamEnv<'tcx>,
32 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
33 fn with_fcx<F>(&'tcx mut self, f: F) where
34 F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
35 TyCtxt<'b, 'gcx, 'gcx>) -> Vec<Ty<'tcx>>
39 let param_env = self.param_env;
40 self.inherited.enter(|inh| {
41 let fcx = FnCtxt::new(&inh, param_env, id);
42 if !inh.tcx.features().trivial_bounds {
43 // As predicates are cached rather than obligations, this
44 // needsto be called first so that they are checked with an
46 check_false_global_bounds(&fcx, span, id);
48 let wf_tys = f(&fcx, fcx.tcx.global_tcx());
49 fcx.select_all_obligations_or_error();
50 fcx.regionck_item(id, span, &wf_tys);
55 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
56 /// well-formed, meaning that they do not require any constraints not declared in the struct
57 /// definition itself. For example, this definition would be illegal:
59 /// struct Ref<'a, T> { x: &'a T }
61 /// because the type did not declare that `T:'a`.
63 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
64 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
66 pub fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
67 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
68 let item = tcx.hir().expect_item_by_hir_id(hir_id);
70 debug!("check_item_well_formed(it.hir_id={:?}, it.name={})",
72 tcx.def_path_str(def_id));
75 // Right now we check that every default trait implementation
76 // has an implementation of itself. Basically, a case like:
78 // `impl Trait for T {}`
80 // has a requirement of `T: Trait` which was required for default
81 // method implementations. Although this could be improved now that
82 // there's a better infrastructure in place for this, it's being left
83 // for a follow-up work.
85 // Since there's such a requirement, we need to check *just* positive
86 // implementations, otherwise things like:
88 // impl !Send for T {}
90 // won't be allowed unless there's an *explicit* implementation of `Send`
92 hir::ItemKind::Impl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
93 let is_auto = tcx.impl_trait_ref(tcx.hir().local_def_id_from_hir_id(item.hir_id))
94 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
95 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
96 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
98 if polarity == hir::ImplPolarity::Positive {
99 check_impl(tcx, item, self_ty, trait_ref);
101 // FIXME(#27579) what amount of WF checking do we need for neg impls?
102 if trait_ref.is_some() && !is_auto {
103 span_err!(tcx.sess, item.span, E0192,
104 "negative impls are only allowed for \
105 auto traits (e.g., `Send` and `Sync`)")
109 hir::ItemKind::Fn(..) => {
110 check_item_fn(tcx, item);
112 hir::ItemKind::Static(ref ty, ..) => {
113 check_item_type(tcx, item.hir_id, ty.span, false);
115 hir::ItemKind::Const(ref ty, ..) => {
116 check_item_type(tcx, item.hir_id, ty.span, false);
118 hir::ItemKind::ForeignMod(ref module) => for it in module.items.iter() {
119 if let hir::ForeignItemKind::Static(ref ty, ..) = it.node {
120 check_item_type(tcx, it.hir_id, ty.span, true);
123 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
124 check_type_defn(tcx, item, false, |fcx| {
125 vec![fcx.non_enum_variant(struct_def)]
128 check_variances_for_type_defn(tcx, item, ast_generics);
130 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
131 check_type_defn(tcx, item, true, |fcx| {
132 vec![fcx.non_enum_variant(struct_def)]
135 check_variances_for_type_defn(tcx, item, ast_generics);
137 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
138 check_type_defn(tcx, item, true, |fcx| {
139 fcx.enum_variants(enum_def)
142 check_variances_for_type_defn(tcx, item, ast_generics);
144 hir::ItemKind::Trait(..) => {
145 check_trait(tcx, item);
147 hir::ItemKind::TraitAlias(..) => {
148 check_trait(tcx, item);
154 pub fn check_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
155 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
156 let trait_item = tcx.hir().expect_trait_item(hir_id);
158 let method_sig = match trait_item.node {
159 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
162 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
165 pub fn check_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
166 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
167 let impl_item = tcx.hir().expect_impl_item(hir_id);
169 let method_sig = match impl_item.node {
170 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
173 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
176 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
179 sig_if_method: Option<&hir::MethodSig>) {
180 debug!("check_associated_item: {:?}", item_id);
182 let code = ObligationCauseCode::MiscObligation;
183 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
184 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id_from_hir_id(item_id));
186 let (mut implied_bounds, self_ty) = match item.container {
187 ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
188 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
189 fcx.tcx.type_of(def_id))
193 ty::AssocKind::Const => {
194 let ty = fcx.tcx.type_of(item.def_id);
195 let ty = fcx.normalize_associated_types_in(span, &ty);
196 fcx.register_wf_obligation(ty, span, code.clone());
198 ty::AssocKind::Method => {
199 reject_shadowing_parameters(fcx.tcx, item.def_id);
200 let sig = fcx.tcx.fn_sig(item.def_id);
201 let sig = fcx.normalize_associated_types_in(span, &sig);
202 check_fn_or_method(tcx, fcx, span, sig,
203 item.def_id, &mut implied_bounds);
204 let sig_if_method = sig_if_method.expect("bad signature for method");
205 check_method_receiver(fcx, sig_if_method, &item, self_ty);
207 ty::AssocKind::Type => {
208 if item.defaultness.has_value() {
209 let ty = fcx.tcx.type_of(item.def_id);
210 let ty = fcx.normalize_associated_types_in(span, &ty);
211 fcx.register_wf_obligation(ty, span, code.clone());
214 ty::AssocKind::Existential => {
215 // do nothing, existential types check themselves
223 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
224 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
225 for_id(tcx, item.hir_id, item.span)
228 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: hir::HirId, span: Span)
229 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
230 let def_id = tcx.hir().local_def_id_from_hir_id(id);
232 inherited: Inherited::build(tcx, def_id),
235 param_env: tcx.param_env(def_id),
239 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
240 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
241 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
242 where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
244 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
245 let variants = lookup_fields(fcx);
246 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
247 let packed = fcx.tcx.adt_def(def_id).repr.packed();
249 for variant in &variants {
250 // For DST, or when drop needs to copy things around, all
251 // intermediate types must be sized.
252 let needs_drop_copy = || {
254 let ty = variant.fields.last().unwrap().ty;
255 fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
256 .map(|ty| ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id)))
258 fcx_tcx.sess.delay_span_bug(
259 item.span, &format!("inference variables in {:?}", ty));
260 // Just treat unresolved type expression as if it needs drop.
267 variant.fields.is_empty() ||
269 let unsized_len = if all_sized {
274 for (idx, field) in variant.fields[..variant.fields.len() - unsized_len]
278 let last = idx == variant.fields.len() - 1;
281 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
282 traits::ObligationCause::new(
286 adt_kind: match item.node.adt_kind() {
296 // All field types must be well-formed.
297 for field in &variant.fields {
298 fcx.register_wf_obligation(field.ty, field.span,
299 ObligationCauseCode::MiscObligation)
303 check_where_clauses(tcx, fcx, item.span, def_id, None);
305 vec![] // no implied bounds in a struct def'n
309 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
310 debug!("check_trait: {:?}", item.hir_id);
312 let trait_def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id);
314 let trait_def = tcx.trait_def(trait_def_id);
315 if trait_def.is_marker {
316 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
319 tcx.def_span(*associated_def_id),
321 "marker traits cannot have associated items",
326 for_item(tcx, item).with_fcx(|fcx, _| {
327 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
332 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
333 for_item(tcx, item).with_fcx(|fcx, tcx| {
334 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
335 let sig = fcx.tcx.fn_sig(def_id);
336 let sig = fcx.normalize_associated_types_in(item.span, &sig);
337 let mut implied_bounds = vec![];
338 check_fn_or_method(tcx, fcx, item.span, sig,
339 def_id, &mut implied_bounds);
344 fn check_item_type<'a, 'tcx>(
345 tcx: TyCtxt<'a, 'tcx, 'tcx>,
348 allow_foreign_ty: bool,
350 debug!("check_item_type: {:?}", item_id);
352 for_id(tcx, item_id, ty_span).with_fcx(|fcx, gcx| {
353 let ty = gcx.type_of(gcx.hir().local_def_id_from_hir_id(item_id));
354 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
356 let mut forbid_unsized = true;
357 if allow_foreign_ty {
358 if let ty::Foreign(_) = fcx.tcx.struct_tail(item_ty).sty {
359 forbid_unsized = false;
363 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
367 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
368 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
372 vec![] // no implied bounds in a const etc
376 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
378 ast_self_ty: &hir::Ty,
379 ast_trait_ref: &Option<hir::TraitRef>)
381 debug!("check_impl: {:?}", item);
383 for_item(tcx, item).with_fcx(|fcx, tcx| {
384 let item_def_id = fcx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
386 match *ast_trait_ref {
387 Some(ref ast_trait_ref) => {
388 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
390 fcx.normalize_associated_types_in(
391 ast_trait_ref.path.span, &trait_ref);
393 ty::wf::trait_obligations(fcx,
397 ast_trait_ref.path.span);
398 for obligation in obligations {
399 fcx.register_predicate(obligation);
403 let self_ty = fcx.tcx.type_of(item_def_id);
404 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
405 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
406 ObligationCauseCode::MiscObligation);
410 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
412 fcx.impl_implied_bounds(item_def_id, item.span)
416 /// Checks where-clauses and inline bounds that are declared on `def_id`.
417 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
418 tcx: TyCtxt<'a, 'gcx, 'gcx>,
419 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
422 return_ty: Option<Ty<'tcx>>,
424 let predicates = fcx.tcx.predicates_of(def_id);
425 let generics = tcx.generics_of(def_id);
427 let is_our_default = |def: &ty::GenericParamDef| {
429 GenericParamDefKind::Type { has_default, .. } => {
430 has_default && def.index >= generics.parent_count as u32
436 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
437 // For example this forbids the declaration:
438 // struct Foo<T = Vec<[u32]>> { .. }
439 // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
440 for param in &generics.params {
441 if let GenericParamDefKind::Type { .. } = param.kind {
442 if is_our_default(¶m) {
443 let ty = fcx.tcx.type_of(param.def_id);
444 // ignore dependent defaults -- that is, where the default of one type
445 // parameter includes another (e.g., <T, U = T>). In those cases, we can't
446 // be sure if it will error or not as user might always specify the other.
447 if !ty.needs_subst() {
448 fcx.register_wf_obligation(ty, fcx.tcx.def_span(param.def_id),
449 ObligationCauseCode::MiscObligation);
455 // Check that trait predicates are WF when params are substituted by their defaults.
456 // We don't want to overly constrain the predicates that may be written but we want to
457 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
458 // Therefore we check if a predicate which contains a single type param
459 // with a concrete default is WF with that default substituted.
460 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
462 // First we build the defaulted substitution.
463 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
465 GenericParamDefKind::Lifetime => {
466 // All regions are identity.
467 fcx.tcx.mk_param_from_def(param)
470 GenericParamDefKind::Type { .. } => {
471 // If the param has a default,
472 if is_our_default(param) {
473 let default_ty = fcx.tcx.type_of(param.def_id);
474 // and it's not a dependent default
475 if !default_ty.needs_subst() {
476 // then substitute with the default.
477 return default_ty.into();
480 // Mark unwanted params as err.
481 fcx.tcx.types.err.into()
484 GenericParamDefKind::Const => {
485 // FIXME(const_generics:defaults)
486 fcx.tcx.consts.err.into()
491 // Now we build the substituted predicates.
492 let default_obligations = predicates.predicates.iter().flat_map(|&(pred, _)| {
494 struct CountParams { params: FxHashSet<u32> }
495 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
496 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
497 if let ty::Param(param) = t.sty {
498 self.params.insert(param.index);
500 t.super_visit_with(self)
503 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
507 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
508 if let ConstValue::Param(param) = c.val {
509 self.params.insert(param.index);
511 c.super_visit_with(self)
514 let mut param_count = CountParams::default();
515 let has_region = pred.visit_with(&mut param_count);
516 let substituted_pred = pred.subst(fcx.tcx, substs);
517 // Don't check non-defaulted params, dependent defaults (including lifetimes)
518 // or preds with multiple params.
519 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
521 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
522 // Avoid duplication of predicates that contain no parameters, for example.
525 Some(substituted_pred)
528 // convert each of those into an obligation. So if you have
529 // something like `struct Foo<T: Copy = String>`, we would
530 // take that predicate `T: Copy`, substitute to `String: Copy`
531 // (actually that happens in the previous `flat_map` call),
532 // and then try to prove it (in this case, we'll fail).
534 // Note the subtle difference from how we handle `predicates`
535 // below: there, we are not trying to prove those predicates
536 // to be *true* but merely *well-formed*.
537 let pred = fcx.normalize_associated_types_in(span, &pred);
538 let cause = traits::ObligationCause::new(span, fcx.body_id, traits::ItemObligation(def_id));
539 traits::Obligation::new(cause, fcx.param_env, pred)
542 let mut predicates = predicates.instantiate_identity(fcx.tcx);
544 if let Some(return_ty) = return_ty {
545 predicates.predicates.extend(check_existential_types(tcx, fcx, def_id, span, return_ty));
548 let predicates = fcx.normalize_associated_types_in(span, &predicates);
550 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
552 predicates.predicates
554 .flat_map(|p| ty::wf::predicate_obligations(fcx,
560 for obligation in wf_obligations.chain(default_obligations) {
561 debug!("next obligation cause: {:?}", obligation.cause);
562 fcx.register_predicate(obligation);
566 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
567 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
569 sig: ty::PolyFnSig<'tcx>,
571 implied_bounds: &mut Vec<Ty<'tcx>>)
573 let sig = fcx.normalize_associated_types_in(span, &sig);
574 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
576 for input_ty in sig.inputs() {
577 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
579 implied_bounds.extend(sig.inputs());
581 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
583 // FIXME(#25759) return types should not be implied bounds
584 implied_bounds.push(sig.output());
586 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
589 /// Checks "defining uses" of existential types to ensure that they meet the restrictions laid for
590 /// "higher-order pattern unification".
591 /// This ensures that inference is tractable.
592 /// In particular, definitions of existential types can only use other generics as arguments,
593 /// and they cannot repeat an argument. Example:
596 /// existential type Foo<A, B>;
598 /// // ok -- `Foo` is applied to two distinct, generic types.
599 /// fn a<T, U>() -> Foo<T, U> { .. }
601 /// // not ok -- `Foo` is applied to `T` twice.
602 /// fn b<T>() -> Foo<T, T> { .. }
605 /// // not ok -- `Foo` is applied to a non-generic type.
606 /// fn b<T>() -> Foo<T, u32> { .. }
609 fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>(
610 tcx: TyCtxt<'a, 'gcx, 'gcx>,
611 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
615 ) -> Vec<ty::Predicate<'tcx>> {
616 trace!("check_existential_types: {:?}", ty);
617 let mut substituted_predicates = Vec::new();
618 ty.fold_with(&mut ty::fold::BottomUpFolder {
621 if let ty::Opaque(def_id, substs) = ty.sty {
622 trace!("check_existential_types: opaque_ty, {:?}, {:?}", def_id, substs);
623 let generics = tcx.generics_of(def_id);
624 // only check named existential types defined in this crate
625 if generics.parent.is_none() && def_id.is_local() {
626 let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
627 if may_define_existential_type(tcx, fn_def_id, opaque_hir_id) {
628 trace!("check_existential_types may define. Generics: {:#?}", generics);
629 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
630 for (subst, param) in substs.iter().zip(&generics.params) {
631 match subst.unpack() {
632 ty::subst::UnpackedKind::Type(ty) => match ty.sty {
634 // prevent `fn foo() -> Foo<u32>` from being defining
639 "non-defining existential type use \
643 tcx.def_span(param.def_id),
645 "used non-generic type {} for \
654 ty::subst::UnpackedKind::Lifetime(region) => {
655 let param_span = tcx.def_span(param.def_id);
656 if let ty::ReStatic = region {
661 "non-defining existential type use \
666 "cannot use static lifetime, use a bound lifetime \
667 instead or remove the lifetime parameter from the \
672 seen.entry(region).or_default().push(param_span);
676 ty::subst::UnpackedKind::Const(ct) => match ct.val {
677 ConstValue::Param(_) => {}
682 "non-defining existential type use \
686 tcx.def_span(param.def_id),
688 "used non-generic const {} for \
697 } // for (subst, param)
698 for (_, spans) in seen {
704 "non-defining existential type use \
709 "lifetime used multiple times",
714 } // if may_define_existential_type
716 // now register the bounds on the parameters of the existential type
717 // so the parameters given by the function need to fulfill them
719 // existential type Foo<T: Bar>: 'static;
720 // fn foo<U>() -> Foo<U> { .. *}
724 // existential type Foo<T: Bar>: 'static;
725 // fn foo<U: Bar>() -> Foo<U> { .. *}
727 let predicates = tcx.predicates_of(def_id);
729 "check_existential_types may define. adding predicates: {:#?}",
732 for &(pred, _) in predicates.predicates.iter() {
733 let substituted_pred = pred.subst(fcx.tcx, substs);
734 // Avoid duplication of predicates that contain no parameters, for example.
735 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
736 substituted_predicates.push(substituted_pred);
739 } // if is_named_existential_type
746 substituted_predicates
749 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
750 method_sig: &hir::MethodSig,
751 method: &ty::AssocItem,
754 // check that the method has a valid receiver type, given the type `Self`
755 debug!("check_method_receiver({:?}, self_ty={:?})",
758 if !method.method_has_self_argument {
762 let span = method_sig.decl.inputs[0].span;
764 let sig = fcx.tcx.fn_sig(method.def_id);
765 let sig = fcx.normalize_associated_types_in(span, &sig);
766 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
768 debug!("check_method_receiver: sig={:?}", sig);
770 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
771 let self_ty = fcx.tcx.liberate_late_bound_regions(
773 &ty::Binder::bind(self_ty)
776 let receiver_ty = sig.inputs()[0];
778 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
779 let receiver_ty = fcx.tcx.liberate_late_bound_regions(
781 &ty::Binder::bind(receiver_ty)
784 if fcx.tcx.features().arbitrary_self_types {
785 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
786 // report error, arbitrary_self_types was enabled
787 fcx.tcx.sess.diagnostic().mut_span_err(
788 span, &format!("invalid method receiver type: {:?}", receiver_ty)
789 ).note("type of `self` must be `Self` or a type that dereferences to it")
790 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
791 .code(DiagnosticId::Error("E0307".into()))
795 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
796 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
797 // report error, would have worked with arbitrary_self_types
798 feature_gate::feature_err(
799 &fcx.tcx.sess.parse_sess,
800 sym::arbitrary_self_types,
804 "`{}` cannot be used as the type of `self` without \
805 the `arbitrary_self_types` feature",
808 ).help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
811 // report error, would not have worked with arbitrary_self_types
812 fcx.tcx.sess.diagnostic().mut_span_err(
813 span, &format!("invalid method receiver type: {:?}", receiver_ty)
814 ).note("type must be `Self` or a type that dereferences to it")
815 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
816 .code(DiagnosticId::Error("E0307".into()))
823 /// returns true if `receiver_ty` would be considered a valid receiver type for `self_ty`. If
824 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
825 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
826 /// strict: `receiver_ty` must implement `Receiver` and directly implement `Deref<Target=self_ty>`.
828 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
829 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
830 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
831 fn receiver_is_valid<'fcx, 'tcx, 'gcx>(
832 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
834 receiver_ty: Ty<'tcx>,
836 arbitrary_self_types_enabled: bool,
838 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
840 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
842 // `self: Self` is always valid
843 if can_eq_self(receiver_ty) {
844 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
850 let mut autoderef = fcx.autoderef(span, receiver_ty);
852 // the `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`
853 if arbitrary_self_types_enabled {
854 autoderef = autoderef.include_raw_pointers();
857 // the first type is `receiver_ty`, which we know its not equal to `self_ty`. skip it.
860 // keep dereferencing `receiver_ty` until we get to `self_ty`
862 if let Some((potential_self_ty, _)) = autoderef.next() {
863 debug!("receiver_is_valid: potential self type `{:?}` to match `{:?}`",
864 potential_self_ty, self_ty);
866 if can_eq_self(potential_self_ty) {
867 autoderef.finalize(fcx);
869 if let Some(mut err) = fcx.demand_eqtype_with_origin(
870 &cause, self_ty, potential_self_ty
878 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`",
879 receiver_ty, self_ty);
880 // If he receiver already has errors reported due to it, consider it valid to avoid
881 // unecessary errors (#58712).
882 return receiver_ty.references_error();
885 // without the `arbitrary_self_types` feature, `receiver_ty` must directly deref to
886 // `self_ty`. Enforce this by only doing one iteration of the loop
887 if !arbitrary_self_types_enabled {
892 // without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`
893 if !arbitrary_self_types_enabled {
894 let trait_def_id = match fcx.tcx.lang_items().receiver_trait() {
897 debug!("receiver_is_valid: missing Receiver trait");
902 let trait_ref = ty::TraitRef{
903 def_id: trait_def_id,
904 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
907 let obligation = traits::Obligation::new(
910 trait_ref.to_predicate()
913 if !fcx.predicate_must_hold_modulo_regions(&obligation) {
914 debug!("receiver_is_valid: type `{:?}` does not implement `Receiver` trait",
923 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
925 hir_generics: &hir::Generics)
927 let item_def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id);
928 let ty = tcx.type_of(item_def_id);
929 if tcx.has_error_field(ty) {
933 let ty_predicates = tcx.predicates_of(item_def_id);
934 assert_eq!(ty_predicates.parent, None);
935 let variances = tcx.variances_of(item_def_id);
937 let mut constrained_parameters: FxHashSet<_> =
938 variances.iter().enumerate()
939 .filter(|&(_, &variance)| variance != ty::Bivariant)
940 .map(|(index, _)| Parameter(index as u32))
943 identify_constrained_generic_params(
947 &mut constrained_parameters,
950 for (index, _) in variances.iter().enumerate() {
951 if constrained_parameters.contains(&Parameter(index as u32)) {
955 let param = &hir_generics.params[index];
958 hir::ParamName::Error => { }
959 _ => report_bivariance(tcx, param.span, param.name.ident().name),
964 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
966 param_name: ast::Name)
968 let mut err = error_392(tcx, span, param_name);
970 let suggested_marker_id = tcx.lang_items().phantom_data();
971 // help is available only in presence of lang items
972 if let Some(def_id) = suggested_marker_id {
973 err.help(&format!("consider removing `{}` or using a marker such as `{}`",
975 tcx.def_path_str(def_id)));
980 fn reject_shadowing_parameters(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) {
981 let generics = tcx.generics_of(def_id);
982 let parent = tcx.generics_of(generics.parent.unwrap());
983 let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
984 GenericParamDefKind::Lifetime => None,
985 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
986 Some((param.name, param.def_id))
990 for method_param in &generics.params {
991 // Shadowing is checked in resolve_lifetime.
992 if let GenericParamDefKind::Lifetime = method_param.kind {
995 if impl_params.contains_key(&method_param.name) {
996 // Tighten up the span to focus on only the shadowing type
997 let type_span = tcx.def_span(method_param.def_id);
999 // The expectation here is that the original trait declaration is
1000 // local so it should be okay to just unwrap everything.
1001 let trait_def_id = impl_params[&method_param.name];
1002 let trait_decl_span = tcx.def_span(trait_def_id);
1003 error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
1008 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1010 fn check_false_global_bounds<'a, 'gcx, 'tcx>(
1011 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1015 let empty_env = ty::ParamEnv::empty();
1017 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(id);
1018 let predicates = fcx.tcx.predicates_of(def_id).predicates
1022 // Check elaborated bounds.
1023 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1025 for pred in implied_obligations {
1026 // Match the existing behavior.
1027 if pred.is_global() && !pred.has_late_bound_regions() {
1028 let pred = fcx.normalize_associated_types_in(span, &pred);
1029 let obligation = traits::Obligation::new(
1030 traits::ObligationCause::new(
1033 traits::TrivialBound,
1038 fcx.register_predicate(obligation);
1042 fcx.select_all_obligations_or_error();
1045 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
1046 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1049 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
1050 pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
1051 -> CheckTypeWellFormedVisitor<'a, 'gcx> {
1052 CheckTypeWellFormedVisitor {
1058 impl<'a, 'tcx> ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'a, 'tcx> {
1059 fn visit_item(&self, i: &'tcx hir::Item) {
1060 debug!("visit_item: {:?}", i);
1061 let def_id = self.tcx.hir().local_def_id_from_hir_id(i.hir_id);
1062 self.tcx.ensure().check_item_well_formed(def_id);
1065 fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem) {
1066 debug!("visit_trait_item: {:?}", trait_item);
1067 let def_id = self.tcx.hir().local_def_id_from_hir_id(trait_item.hir_id);
1068 self.tcx.ensure().check_trait_item_well_formed(def_id);
1071 fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem) {
1072 debug!("visit_impl_item: {:?}", impl_item);
1073 let def_id = self.tcx.hir().local_def_id_from_hir_id(impl_item.hir_id);
1074 self.tcx.ensure().check_impl_item_well_formed(def_id);
1078 ///////////////////////////////////////////////////////////////////////////
1081 struct AdtVariant<'tcx> {
1082 fields: Vec<AdtField<'tcx>>,
1085 struct AdtField<'tcx> {
1090 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1091 fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
1092 let fields = struct_def.fields().iter().map(|field| {
1093 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id_from_hir_id(field.hir_id));
1094 let field_ty = self.normalize_associated_types_in(field.span,
1096 AdtField { ty: field_ty, span: field.span }
1099 AdtVariant { fields }
1102 fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
1103 enum_def.variants.iter()
1104 .map(|variant| self.non_enum_variant(&variant.node.data))
1108 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1109 match self.tcx.impl_trait_ref(impl_def_id) {
1110 Some(ref trait_ref) => {
1111 // Trait impl: take implied bounds from all types that
1112 // appear in the trait reference.
1113 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1114 trait_ref.substs.types().collect()
1118 // Inherent impl: take implied bounds from the `self` type.
1119 let self_ty = self.tcx.type_of(impl_def_id);
1120 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1127 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
1128 -> DiagnosticBuilder<'tcx> {
1129 let mut err = struct_span_err!(tcx.sess, span, E0392,
1130 "parameter `{}` is never used", param_name);
1131 err.span_label(span, "unused parameter");
1135 fn error_194(tcx: TyCtxt<'_, '_, '_>, span: Span, trait_decl_span: Span, name: &str) {
1136 struct_span_err!(tcx.sess, span, E0194,
1137 "type parameter `{}` shadows another type parameter of the same name",
1139 .span_label(span, "shadows another type parameter")
1140 .span_label(trait_decl_span, format!("first `{}` declared here", name))