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::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 errors::{DiagnosticBuilder, DiagnosticId};
18 use rustc::hir::itemlikevisit::ItemLikeVisitor;
21 /// Helper type of a temporary returned by `.for_item(...)`.
22 /// Necessary because we can't write the following bound:
23 /// `F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>)`.
24 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
25 inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
28 param_env: ty::ParamEnv<'tcx>,
31 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
32 fn with_fcx<F>(&'tcx mut self, f: F) where
33 F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
34 TyCtxt<'b, 'gcx, 'gcx>) -> Vec<Ty<'tcx>>
38 let param_env = self.param_env;
39 self.inherited.enter(|inh| {
40 let fcx = FnCtxt::new(&inh, param_env, id);
41 if !inh.tcx.features().trivial_bounds {
42 // As predicates are cached rather than obligations, this
43 // needsto be called first so that they are checked with an
45 check_false_global_bounds(&fcx, span, id);
47 let wf_tys = f(&fcx, fcx.tcx.global_tcx());
48 fcx.select_all_obligations_or_error();
49 fcx.regionck_item(id, span, &wf_tys);
54 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
55 /// well-formed, meaning that they do not require any constraints not declared in the struct
56 /// definition itself. For example, this definition would be illegal:
58 /// struct Ref<'a, T> { x: &'a T }
60 /// because the type did not declare that `T:'a`.
62 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
63 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
65 pub fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
66 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
67 let item = tcx.hir().expect_item_by_hir_id(hir_id);
69 debug!("check_item_well_formed(it.hir_id={:?}, it.name={})",
71 tcx.item_path_str(def_id));
74 // Right now we check that every default trait implementation
75 // has an implementation of itself. Basically, a case like:
77 // `impl Trait for T {}`
79 // has a requirement of `T: Trait` which was required for default
80 // method implementations. Although this could be improved now that
81 // there's a better infrastructure in place for this, it's being left
82 // for a follow-up work.
84 // Since there's such a requirement, we need to check *just* positive
85 // implementations, otherwise things like:
87 // impl !Send for T {}
89 // won't be allowed unless there's an *explicit* implementation of `Send`
91 hir::ItemKind::Impl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
92 let is_auto = tcx.impl_trait_ref(tcx.hir().local_def_id_from_hir_id(item.hir_id))
93 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
94 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
95 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
97 if polarity == hir::ImplPolarity::Positive {
98 check_impl(tcx, item, self_ty, trait_ref);
100 // FIXME(#27579) what amount of WF checking do we need for neg impls?
101 if trait_ref.is_some() && !is_auto {
102 span_err!(tcx.sess, item.span, E0192,
103 "negative impls are only allowed for \
104 auto traits (e.g., `Send` and `Sync`)")
108 hir::ItemKind::Fn(..) => {
109 check_item_fn(tcx, item);
111 hir::ItemKind::Static(ref ty, ..) => {
112 check_item_type(tcx, item.hir_id, ty.span, false);
114 hir::ItemKind::Const(ref ty, ..) => {
115 check_item_type(tcx, item.hir_id, ty.span, false);
117 hir::ItemKind::ForeignMod(ref module) => for it in module.items.iter() {
118 if let hir::ForeignItemKind::Static(ref ty, ..) = it.node {
119 check_item_type(tcx, it.hir_id, ty.span, true);
122 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
123 check_type_defn(tcx, item, false, |fcx| {
124 vec![fcx.non_enum_variant(struct_def)]
127 check_variances_for_type_defn(tcx, item, ast_generics);
129 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
130 check_type_defn(tcx, item, true, |fcx| {
131 vec![fcx.non_enum_variant(struct_def)]
134 check_variances_for_type_defn(tcx, item, ast_generics);
136 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
137 check_type_defn(tcx, item, true, |fcx| {
138 fcx.enum_variants(enum_def)
141 check_variances_for_type_defn(tcx, item, ast_generics);
143 hir::ItemKind::Trait(..) => {
144 check_trait(tcx, item);
146 hir::ItemKind::TraitAlias(..) => {
147 check_trait(tcx, item);
153 pub fn check_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
154 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
155 let trait_item = tcx.hir().expect_trait_item(node_id);
157 let method_sig = match trait_item.node {
158 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
161 check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
164 pub fn check_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
165 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
166 let impl_item = tcx.hir().expect_impl_item(node_id);
168 let method_sig = match impl_item.node {
169 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
172 check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
175 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
178 sig_if_method: Option<&hir::MethodSig>) {
179 debug!("check_associated_item: {:?}", item_id);
181 let code = ObligationCauseCode::MiscObligation;
182 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
183 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id_from_hir_id(item_id));
185 let (mut implied_bounds, self_ty) = match item.container {
186 ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
187 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
188 fcx.tcx.type_of(def_id))
192 ty::AssociatedKind::Const => {
193 let ty = fcx.tcx.type_of(item.def_id);
194 let ty = fcx.normalize_associated_types_in(span, &ty);
195 fcx.register_wf_obligation(ty, span, code.clone());
197 ty::AssociatedKind::Method => {
198 reject_shadowing_parameters(fcx.tcx, item.def_id);
199 let sig = fcx.tcx.fn_sig(item.def_id);
200 let sig = fcx.normalize_associated_types_in(span, &sig);
201 check_fn_or_method(tcx, fcx, span, sig,
202 item.def_id, &mut implied_bounds);
203 let sig_if_method = sig_if_method.expect("bad signature for method");
204 check_method_receiver(fcx, sig_if_method, &item, self_ty);
206 ty::AssociatedKind::Type => {
207 if item.defaultness.has_value() {
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());
213 ty::AssociatedKind::Existential => {
214 // do nothing, existential types check themselves
222 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
223 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
224 for_id(tcx, item.hir_id, item.span)
227 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: hir::HirId, span: Span)
228 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
229 let def_id = tcx.hir().local_def_id_from_hir_id(id);
231 inherited: Inherited::build(tcx, def_id),
234 param_env: tcx.param_env(def_id),
238 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
239 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
240 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
241 where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
243 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
244 let variants = lookup_fields(fcx);
245 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
246 let packed = fcx.tcx.adt_def(def_id).repr.packed();
248 for variant in &variants {
249 // For DST, or when drop needs to copy things around, all
250 // intermediate types must be sized.
251 let needs_drop_copy = || {
253 let ty = variant.fields.last().unwrap().ty;
254 let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
256 span_bug!(item.span, "inference variables in {:?}", ty)
258 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
263 variant.fields.is_empty() ||
265 let unsized_len = if all_sized {
270 for (idx, field) in variant.fields[..variant.fields.len() - unsized_len]
274 let last = idx == variant.fields.len() - 1;
277 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
278 traits::ObligationCause::new(
282 adt_kind: match item.node.adt_kind() {
292 // All field types must be well-formed.
293 for field in &variant.fields {
294 fcx.register_wf_obligation(field.ty, field.span,
295 ObligationCauseCode::MiscObligation)
299 check_where_clauses(tcx, fcx, item.span, def_id, None);
301 vec![] // no implied bounds in a struct def'n
305 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
306 debug!("check_trait: {:?}", item.hir_id);
308 let trait_def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id);
310 let trait_def = tcx.trait_def(trait_def_id);
311 if trait_def.is_marker {
312 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
315 tcx.def_span(*associated_def_id),
317 "marker traits cannot have associated items",
322 for_item(tcx, item).with_fcx(|fcx, _| {
323 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
328 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
329 for_item(tcx, item).with_fcx(|fcx, tcx| {
330 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
331 let sig = fcx.tcx.fn_sig(def_id);
332 let sig = fcx.normalize_associated_types_in(item.span, &sig);
333 let mut implied_bounds = vec![];
334 check_fn_or_method(tcx, fcx, item.span, sig,
335 def_id, &mut implied_bounds);
340 fn check_item_type<'a, 'tcx>(
341 tcx: TyCtxt<'a, 'tcx, 'tcx>,
344 allow_foreign_ty: bool,
346 debug!("check_item_type: {:?}", item_id);
348 for_id(tcx, item_id, ty_span).with_fcx(|fcx, gcx| {
349 let ty = gcx.type_of(gcx.hir().local_def_id_from_hir_id(item_id));
350 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
352 let mut forbid_unsized = true;
353 if allow_foreign_ty {
354 if let TyKind::Foreign(_) = fcx.tcx.struct_tail(item_ty).sty {
355 forbid_unsized = false;
359 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
363 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
364 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
368 vec![] // no implied bounds in a const etc
372 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
374 ast_self_ty: &hir::Ty,
375 ast_trait_ref: &Option<hir::TraitRef>)
377 debug!("check_impl: {:?}", item);
379 for_item(tcx, item).with_fcx(|fcx, tcx| {
380 let item_def_id = fcx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
382 match *ast_trait_ref {
383 Some(ref ast_trait_ref) => {
384 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
386 fcx.normalize_associated_types_in(
387 ast_trait_ref.path.span, &trait_ref);
389 ty::wf::trait_obligations(fcx,
393 ast_trait_ref.path.span);
394 for obligation in obligations {
395 fcx.register_predicate(obligation);
399 let self_ty = fcx.tcx.type_of(item_def_id);
400 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
401 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
402 ObligationCauseCode::MiscObligation);
406 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
408 fcx.impl_implied_bounds(item_def_id, item.span)
412 /// Checks where-clauses and inline bounds that are declared on `def_id`.
413 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
414 tcx: TyCtxt<'a, 'gcx, 'gcx>,
415 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
418 return_ty: Option<Ty<'tcx>>,
420 use ty::subst::Subst;
421 use rustc::ty::TypeFoldable;
423 let predicates = fcx.tcx.predicates_of(def_id);
425 let generics = tcx.generics_of(def_id);
426 let is_our_default = |def: &ty::GenericParamDef| {
428 GenericParamDefKind::Type { has_default, .. } => {
429 has_default && def.index >= generics.parent_count as u32
435 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
436 // For example this forbids the declaration:
437 // struct Foo<T = Vec<[u32]>> { .. }
438 // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
439 for param in &generics.params {
440 if let GenericParamDefKind::Type { .. } = param.kind {
441 if is_our_default(¶m) {
442 let ty = fcx.tcx.type_of(param.def_id);
443 // ignore dependent defaults -- that is, where the default of one type
444 // parameter includes another (e.g., <T, U = T>). In those cases, we can't
445 // be sure if it will error or not as user might always specify the other.
446 if !ty.needs_subst() {
447 fcx.register_wf_obligation(ty, fcx.tcx.def_span(param.def_id),
448 ObligationCauseCode::MiscObligation);
454 // Check that trait predicates are WF when params are substituted by their defaults.
455 // We don't want to overly constrain the predicates that may be written but we want to
456 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
457 // Therefore we check if a predicate which contains a single type param
458 // with a concrete default is WF with that default substituted.
459 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
461 // First we build the defaulted substitution.
462 let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
464 GenericParamDefKind::Lifetime => {
465 // All regions are identity.
466 fcx.tcx.mk_param_from_def(param)
468 GenericParamDefKind::Type { .. } => {
469 // If the param has a default,
470 if is_our_default(param) {
471 let default_ty = fcx.tcx.type_of(param.def_id);
472 // and it's not a dependent default
473 if !default_ty.needs_subst() {
474 // then substitute with the default.
475 return default_ty.into();
478 // Mark unwanted params as err.
479 fcx.tcx.types.err.into()
481 GenericParamDefKind::Const => {
482 // FIXME(const_generics:defaults)
483 fcx.tcx.types.err.into()
487 // Now we build the substituted predicates.
488 let default_obligations = predicates.predicates.iter().flat_map(|&(pred, _)| {
490 struct CountParams { params: FxHashSet<u32> }
491 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
492 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
495 self.params.insert(p.idx);
496 t.super_visit_with(self)
498 _ => t.super_visit_with(self)
502 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
506 fn visit_const(&mut self, c: &'tcx ty::LazyConst<'tcx>) -> bool {
507 if let ty::LazyConst::Evaluated(ty::Const {
508 val: ConstValue::Param(param),
511 self.params.insert(param.index);
513 c.super_visit_with(self)
516 let mut param_count = CountParams::default();
517 let has_region = pred.visit_with(&mut param_count);
518 let substituted_pred = pred.subst(fcx.tcx, substs);
519 // Don't check non-defaulted params, dependent defaults (including lifetimes)
520 // or preds with multiple params.
521 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
523 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
524 // Avoid duplication of predicates that contain no parameters, for example.
527 Some(substituted_pred)
530 // convert each of those into an obligation. So if you have
531 // something like `struct Foo<T: Copy = String>`, we would
532 // take that predicate `T: Copy`, substitute to `String: Copy`
533 // (actually that happens in the previous `flat_map` call),
534 // and then try to prove it (in this case, we'll fail).
536 // Note the subtle difference from how we handle `predicates`
537 // below: there, we are not trying to prove those predicates
538 // to be *true* but merely *well-formed*.
539 let pred = fcx.normalize_associated_types_in(span, &pred);
540 let cause = traits::ObligationCause::new(span, fcx.body_id, traits::ItemObligation(def_id));
541 traits::Obligation::new(cause, fcx.param_env, pred)
544 let mut predicates = predicates.instantiate_identity(fcx.tcx);
546 if let Some(return_ty) = return_ty {
547 predicates.predicates.extend(check_existential_types(tcx, fcx, def_id, span, return_ty));
550 let predicates = fcx.normalize_associated_types_in(span, &predicates);
552 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
554 predicates.predicates
556 .flat_map(|p| ty::wf::predicate_obligations(fcx,
562 for obligation in wf_obligations.chain(default_obligations) {
563 debug!("next obligation cause: {:?}", obligation.cause);
564 fcx.register_predicate(obligation);
568 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
569 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
571 sig: ty::PolyFnSig<'tcx>,
573 implied_bounds: &mut Vec<Ty<'tcx>>)
575 let sig = fcx.normalize_associated_types_in(span, &sig);
576 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
578 for input_ty in sig.inputs() {
579 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
581 implied_bounds.extend(sig.inputs());
583 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
585 // FIXME(#25759) return types should not be implied bounds
586 implied_bounds.push(sig.output());
588 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
591 /// Checks "defining uses" of existential types to ensure that they meet the restrictions laid for
592 /// "higher-order pattern unification".
593 /// This ensures that inference is tractable.
594 /// In particular, definitions of existential types can only use other generics as arguments,
595 /// and they cannot repeat an argument. Example:
598 /// existential type Foo<A, B>;
600 /// // ok -- `Foo` is applied to two distinct, generic types.
601 /// fn a<T, U>() -> Foo<T, U> { .. }
603 /// // not ok -- `Foo` is applied to `T` twice.
604 /// fn b<T>() -> Foo<T, T> { .. }
607 /// // not ok -- `Foo` is applied to a non-generic type.
608 /// fn b<T>() -> Foo<T, u32> { .. }
611 fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>(
612 tcx: TyCtxt<'a, 'gcx, 'gcx>,
613 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
617 ) -> Vec<ty::Predicate<'tcx>> {
618 trace!("check_existential_types: {:?}, {:?}", ty, ty.sty);
619 let mut substituted_predicates = Vec::new();
620 ty.fold_with(&mut ty::fold::BottomUpFolder {
623 if let ty::Opaque(def_id, substs) = ty.sty {
624 trace!("check_existential_types: opaque_ty, {:?}, {:?}", def_id, substs);
625 let generics = tcx.generics_of(def_id);
626 // only check named existential types defined in this crate
627 if generics.parent.is_none() && def_id.is_local() {
628 let opaque_node_id = tcx.hir().as_local_node_id(def_id).unwrap();
629 if may_define_existential_type(tcx, fn_def_id, opaque_node_id) {
630 trace!("check_existential_types may define. Generics: {:#?}", generics);
631 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
632 for (subst, param) in substs.iter().zip(&generics.params) {
633 match subst.unpack() {
634 ty::subst::UnpackedKind::Type(ty) => match ty.sty {
636 // prevent `fn foo() -> Foo<u32>` from being defining
641 "non-defining existential type use \
645 tcx.def_span(param.def_id),
647 "used non-generic type {} for \
656 ty::subst::UnpackedKind::Lifetime(region) => {
657 let param_span = tcx.def_span(param.def_id);
658 if let ty::ReStatic = region {
663 "non-defining existential type use \
668 "cannot use static lifetime, use a bound lifetime \
669 instead or remove the lifetime parameter from the \
674 seen.entry(region).or_default().push(param_span);
678 ty::subst::UnpackedKind::Const(ct) => match ct {
679 ty::LazyConst::Evaluated(ty::Const {
680 val: ConstValue::Param(_),
687 "non-defining existential type use \
691 tcx.def_span(param.def_id),
693 "used non-generic const {} for \
702 } // for (subst, param)
703 for (_, spans) in seen {
709 "non-defining existential type use \
714 "lifetime used multiple times",
719 } // if may_define_existential_type
721 // now register the bounds on the parameters of the existential type
722 // so the parameters given by the function need to fulfill them
724 // existential type Foo<T: Bar>: 'static;
725 // fn foo<U>() -> Foo<U> { .. *}
729 // existential type Foo<T: Bar>: 'static;
730 // fn foo<U: Bar>() -> Foo<U> { .. *}
732 let predicates = tcx.predicates_of(def_id);
734 "check_existential_types may define. adding predicates: {:#?}",
737 for &(pred, _) in predicates.predicates.iter() {
738 let substituted_pred = pred.subst(fcx.tcx, substs);
739 // Avoid duplication of predicates that contain no parameters, for example.
740 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
741 substituted_predicates.push(substituted_pred);
744 } // if is_named_existential_type
750 substituted_predicates
753 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
754 method_sig: &hir::MethodSig,
755 method: &ty::AssociatedItem,
758 // check that the method has a valid receiver type, given the type `Self`
759 debug!("check_method_receiver({:?}, self_ty={:?})",
762 if !method.method_has_self_argument {
766 let span = method_sig.decl.inputs[0].span;
768 let sig = fcx.tcx.fn_sig(method.def_id);
769 let sig = fcx.normalize_associated_types_in(span, &sig);
770 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
772 debug!("check_method_receiver: sig={:?}", sig);
774 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
775 let self_ty = fcx.tcx.liberate_late_bound_regions(
777 &ty::Binder::bind(self_ty)
780 let receiver_ty = sig.inputs()[0];
782 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
783 let receiver_ty = fcx.tcx.liberate_late_bound_regions(
785 &ty::Binder::bind(receiver_ty)
788 if fcx.tcx.features().arbitrary_self_types {
789 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
790 // report error, arbitrary_self_types was enabled
791 fcx.tcx.sess.diagnostic().mut_span_err(
792 span, &format!("invalid method receiver type: {:?}", receiver_ty)
793 ).note("type of `self` must be `Self` or a type that dereferences to it")
794 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
795 .code(DiagnosticId::Error("E0307".into()))
799 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
800 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
801 // report error, would have worked with arbitrary_self_types
802 feature_gate::feature_err(
803 &fcx.tcx.sess.parse_sess,
804 "arbitrary_self_types",
808 "`{}` cannot be used as the type of `self` without \
809 the `arbitrary_self_types` feature",
812 ).help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
815 // report error, would not have worked with arbitrary_self_types
816 fcx.tcx.sess.diagnostic().mut_span_err(
817 span, &format!("invalid method receiver type: {:?}", receiver_ty)
818 ).note("type must be `Self` or a type that dereferences to it")
819 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
820 .code(DiagnosticId::Error("E0307".into()))
827 /// returns true if `receiver_ty` would be considered a valid receiver type for `self_ty`. If
828 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
829 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
830 /// strict: `receiver_ty` must implement `Receiver` and directly implement `Deref<Target=self_ty>`.
832 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
833 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
834 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
835 fn receiver_is_valid<'fcx, 'tcx, 'gcx>(
836 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
838 receiver_ty: Ty<'tcx>,
840 arbitrary_self_types_enabled: bool,
842 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
844 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
846 // `self: Self` is always valid
847 if can_eq_self(receiver_ty) {
848 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
854 let mut autoderef = fcx.autoderef(span, receiver_ty);
856 // the `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`
857 if arbitrary_self_types_enabled {
858 autoderef = autoderef.include_raw_pointers();
861 // the first type is `receiver_ty`, which we know its not equal to `self_ty`. skip it.
864 // keep dereferencing `receiver_ty` until we get to `self_ty`
866 if let Some((potential_self_ty, _)) = autoderef.next() {
867 debug!("receiver_is_valid: potential self type `{:?}` to match `{:?}`",
868 potential_self_ty, self_ty);
870 if can_eq_self(potential_self_ty) {
871 autoderef.finalize(fcx);
873 if let Some(mut err) = fcx.demand_eqtype_with_origin(
874 &cause, self_ty, potential_self_ty
882 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`",
883 receiver_ty, self_ty);
884 // If he receiver already has errors reported due to it, consider it valid to avoid
885 // unecessary errors (#58712).
886 return receiver_ty.references_error();
889 // without the `arbitrary_self_types` feature, `receiver_ty` must directly deref to
890 // `self_ty`. Enforce this by only doing one iteration of the loop
891 if !arbitrary_self_types_enabled {
896 // without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`
897 if !arbitrary_self_types_enabled {
898 let trait_def_id = match fcx.tcx.lang_items().receiver_trait() {
901 debug!("receiver_is_valid: missing Receiver trait");
906 let trait_ref = ty::TraitRef{
907 def_id: trait_def_id,
908 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
911 let obligation = traits::Obligation::new(
914 trait_ref.to_predicate()
917 if !fcx.predicate_must_hold_modulo_regions(&obligation) {
918 debug!("receiver_is_valid: type `{:?}` does not implement `Receiver` trait",
927 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
929 hir_generics: &hir::Generics)
931 let item_def_id = tcx.hir().local_def_id_from_hir_id(item.hir_id);
932 let ty = tcx.type_of(item_def_id);
933 if tcx.has_error_field(ty) {
937 let ty_predicates = tcx.predicates_of(item_def_id);
938 assert_eq!(ty_predicates.parent, None);
939 let variances = tcx.variances_of(item_def_id);
941 let mut constrained_parameters: FxHashSet<_> =
942 variances.iter().enumerate()
943 .filter(|&(_, &variance)| variance != ty::Bivariant)
944 .map(|(index, _)| Parameter(index as u32))
947 identify_constrained_type_params(tcx,
950 &mut constrained_parameters);
952 for (index, _) in variances.iter().enumerate() {
953 if constrained_parameters.contains(&Parameter(index as u32)) {
957 let param = &hir_generics.params[index];
959 hir::ParamName::Error => { }
960 _ => report_bivariance(tcx, param.span, param.name.ident().name),
965 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
967 param_name: ast::Name)
969 let mut err = error_392(tcx, span, param_name);
971 let suggested_marker_id = tcx.lang_items().phantom_data();
972 // help is available only in presence of lang items
973 if let Some(def_id) = suggested_marker_id {
974 err.help(&format!("consider removing `{}` or using a marker such as `{}`",
976 tcx.item_path_str(def_id)));
981 fn reject_shadowing_parameters(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) {
982 let generics = tcx.generics_of(def_id);
983 let parent = tcx.generics_of(generics.parent.unwrap());
984 let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
985 GenericParamDefKind::Lifetime => None,
986 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
987 Some((param.name, param.def_id))
991 for method_param in &generics.params {
992 // Shadowing is checked in resolve_lifetime.
993 if let GenericParamDefKind::Lifetime = method_param.kind {
996 if impl_params.contains_key(&method_param.name) {
997 // Tighten up the span to focus on only the shadowing type
998 let type_span = tcx.def_span(method_param.def_id);
1000 // The expectation here is that the original trait declaration is
1001 // local so it should be okay to just unwrap everything.
1002 let trait_def_id = impl_params[&method_param.name];
1003 let trait_decl_span = tcx.def_span(trait_def_id);
1004 error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
1009 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1011 fn check_false_global_bounds<'a, 'gcx, 'tcx>(
1012 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
1016 use rustc::ty::TypeFoldable;
1018 let empty_env = ty::ParamEnv::empty();
1020 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(id);
1021 let predicates = fcx.tcx.predicates_of(def_id).predicates
1025 // Check elaborated bounds
1026 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1028 for pred in implied_obligations {
1029 // Match the existing behavior.
1030 if pred.is_global() && !pred.has_late_bound_regions() {
1031 let pred = fcx.normalize_associated_types_in(span, &pred);
1032 let obligation = traits::Obligation::new(
1033 traits::ObligationCause::new(
1036 traits::TrivialBound,
1041 fcx.register_predicate(obligation);
1045 fcx.select_all_obligations_or_error();
1048 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
1049 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1052 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
1053 pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
1054 -> CheckTypeWellFormedVisitor<'a, 'gcx> {
1055 CheckTypeWellFormedVisitor {
1061 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'a, 'tcx> {
1062 fn visit_item(&mut self, i: &'tcx hir::Item) {
1063 debug!("visit_item: {:?}", i);
1064 let def_id = self.tcx.hir().local_def_id_from_hir_id(i.hir_id);
1065 self.tcx.ensure().check_item_well_formed(def_id);
1068 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
1069 debug!("visit_trait_item: {:?}", trait_item);
1070 let def_id = self.tcx.hir().local_def_id_from_hir_id(trait_item.hir_id);
1071 self.tcx.ensure().check_trait_item_well_formed(def_id);
1074 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
1075 debug!("visit_impl_item: {:?}", impl_item);
1076 let def_id = self.tcx.hir().local_def_id_from_hir_id(impl_item.hir_id);
1077 self.tcx.ensure().check_impl_item_well_formed(def_id);
1081 ///////////////////////////////////////////////////////////////////////////
1084 struct AdtVariant<'tcx> {
1085 fields: Vec<AdtField<'tcx>>,
1088 struct AdtField<'tcx> {
1093 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1094 fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
1095 let fields = struct_def.fields().iter().map(|field| {
1096 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id_from_hir_id(field.hir_id));
1097 let field_ty = self.normalize_associated_types_in(field.span,
1099 AdtField { ty: field_ty, span: field.span }
1102 AdtVariant { fields }
1105 fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
1106 enum_def.variants.iter()
1107 .map(|variant| self.non_enum_variant(&variant.node.data))
1111 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1112 match self.tcx.impl_trait_ref(impl_def_id) {
1113 Some(ref trait_ref) => {
1114 // Trait impl: take implied bounds from all types that
1115 // appear in the trait reference.
1116 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1117 trait_ref.substs.types().collect()
1121 // Inherent impl: take implied bounds from the `self` type.
1122 let self_ty = self.tcx.type_of(impl_def_id);
1123 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1130 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
1131 -> DiagnosticBuilder<'tcx> {
1132 let mut err = struct_span_err!(tcx.sess, span, E0392,
1133 "parameter `{}` is never used", param_name);
1134 err.span_label(span, "unused type parameter");
1138 fn error_194(tcx: TyCtxt<'_, '_, '_>, span: Span, trait_decl_span: Span, name: &str) {
1139 struct_span_err!(tcx.sess, span, E0194,
1140 "type parameter `{}` shadows another type parameter of the same name",
1142 .span_label(span, "shadows another type parameter")
1143 .span_label(trait_decl_span, format!("first `{}` declared here", name))