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, Substs};
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.id, ty.span, false);
113 hir::ItemKind::Const(ref ty, ..) => {
114 check_item_type(tcx, item.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.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.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.id, impl_item.span, method_sig);
174 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
175 item_id: ast::NodeId,
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(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.id, item.span)
226 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId, span: Span)
227 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
228 let def_id = tcx.hir().local_def_id(id);
229 let hir_id = tcx.hir().node_to_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(item.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.id);
308 let trait_def_id = tcx.hir().local_def_id(item.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(item.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>,
342 item_id: ast::NodeId,
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(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(item.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 = Substs::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()
483 // Now we build the substituted predicates.
484 let default_obligations = predicates.predicates.iter().flat_map(|&(pred, _)| {
486 struct CountParams { params: FxHashSet<u32> }
487 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
488 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
491 self.params.insert(p.idx);
492 t.super_visit_with(self)
494 _ => t.super_visit_with(self)
498 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
502 let mut param_count = CountParams::default();
503 let has_region = pred.visit_with(&mut param_count);
504 let substituted_pred = pred.subst(fcx.tcx, substs);
505 // Don't check non-defaulted params, dependent defaults (including lifetimes)
506 // or preds with multiple params.
507 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
509 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
510 // Avoid duplication of predicates that contain no parameters, for example.
513 Some(substituted_pred)
516 // convert each of those into an obligation. So if you have
517 // something like `struct Foo<T: Copy = String>`, we would
518 // take that predicate `T: Copy`, substitute to `String: Copy`
519 // (actually that happens in the previous `flat_map` call),
520 // and then try to prove it (in this case, we'll fail).
522 // Note the subtle difference from how we handle `predicates`
523 // below: there, we are not trying to prove those predicates
524 // to be *true* but merely *well-formed*.
525 let pred = fcx.normalize_associated_types_in(span, &pred);
526 let cause = traits::ObligationCause::new(span, fcx.body_id, traits::ItemObligation(def_id));
527 traits::Obligation::new(cause, fcx.param_env, pred)
530 let mut predicates = predicates.instantiate_identity(fcx.tcx);
532 if let Some(return_ty) = return_ty {
533 predicates.predicates.extend(check_existential_types(tcx, fcx, def_id, span, return_ty));
536 let predicates = fcx.normalize_associated_types_in(span, &predicates);
538 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
540 predicates.predicates
542 .flat_map(|p| ty::wf::predicate_obligations(fcx,
548 for obligation in wf_obligations.chain(default_obligations) {
549 debug!("next obligation cause: {:?}", obligation.cause);
550 fcx.register_predicate(obligation);
554 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
555 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
557 sig: ty::PolyFnSig<'tcx>,
559 implied_bounds: &mut Vec<Ty<'tcx>>)
561 let sig = fcx.normalize_associated_types_in(span, &sig);
562 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
564 for input_ty in sig.inputs() {
565 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
567 implied_bounds.extend(sig.inputs());
569 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
571 // FIXME(#25759) return types should not be implied bounds
572 implied_bounds.push(sig.output());
574 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
577 /// Checks "defining uses" of existential types to ensure that they meet the restrictions laid for
578 /// "higher-order pattern unification".
579 /// This ensures that inference is tractable.
580 /// In particular, definitions of existential types can only use other generics as arguments,
581 /// and they cannot repeat an argument. Example:
584 /// existential type Foo<A, B>;
586 /// // ok -- `Foo` is applied to two distinct, generic types.
587 /// fn a<T, U>() -> Foo<T, U> { .. }
589 /// // not ok -- `Foo` is applied to `T` twice.
590 /// fn b<T>() -> Foo<T, T> { .. }
593 /// // not ok -- `Foo` is applied to a non-generic type.
594 /// fn b<T>() -> Foo<T, u32> { .. }
597 fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>(
598 tcx: TyCtxt<'a, 'gcx, 'gcx>,
599 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
603 ) -> Vec<ty::Predicate<'tcx>> {
604 trace!("check_existential_types: {:?}, {:?}", ty, ty.sty);
605 let mut substituted_predicates = Vec::new();
606 ty.fold_with(&mut ty::fold::BottomUpFolder {
609 if let ty::Opaque(def_id, substs) = ty.sty {
610 trace!("check_existential_types: opaque_ty, {:?}, {:?}", def_id, substs);
611 let generics = tcx.generics_of(def_id);
612 // only check named existential types defined in this crate
613 if generics.parent.is_none() && def_id.is_local() {
614 let opaque_node_id = tcx.hir().as_local_node_id(def_id).unwrap();
615 if may_define_existential_type(tcx, fn_def_id, opaque_node_id) {
616 trace!("check_existential_types may define. Generics: {:#?}", generics);
617 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
618 for (subst, param) in substs.iter().zip(&generics.params) {
619 match subst.unpack() {
620 ty::subst::UnpackedKind::Type(ty) => match ty.sty {
622 // prevent `fn foo() -> Foo<u32>` from being defining
628 "non-defining existential type use \
632 tcx.def_span(param.def_id),
634 "used non-generic type {} for \
642 ty::subst::UnpackedKind::Lifetime(region) => {
643 let param_span = tcx.def_span(param.def_id);
644 if let ty::ReStatic = region {
649 "non-defining existential type use \
654 "cannot use static lifetime, use a bound lifetime \
655 instead or remove the lifetime parameter from the \
660 seen.entry(region).or_default().push(param_span);
664 } // for (subst, param)
665 for (_, spans) in seen {
671 "non-defining existential type use \
676 "lifetime used multiple times",
681 } // if may_define_existential_type
683 // now register the bounds on the parameters of the existential type
684 // so the parameters given by the function need to fulfill them
686 // existential type Foo<T: Bar>: 'static;
687 // fn foo<U>() -> Foo<U> { .. *}
691 // existential type Foo<T: Bar>: 'static;
692 // fn foo<U: Bar>() -> Foo<U> { .. *}
694 let predicates = tcx.predicates_of(def_id);
696 "check_existential_types may define. adding predicates: {:#?}",
699 for &(pred, _) in predicates.predicates.iter() {
700 let substituted_pred = pred.subst(fcx.tcx, substs);
701 // Avoid duplication of predicates that contain no parameters, for example.
702 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
703 substituted_predicates.push(substituted_pred);
706 } // if is_named_existential_type
712 substituted_predicates
715 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
716 method_sig: &hir::MethodSig,
717 method: &ty::AssociatedItem,
720 // check that the method has a valid receiver type, given the type `Self`
721 debug!("check_method_receiver({:?}, self_ty={:?})",
724 if !method.method_has_self_argument {
728 let span = method_sig.decl.inputs[0].span;
730 let sig = fcx.tcx.fn_sig(method.def_id);
731 let sig = fcx.normalize_associated_types_in(span, &sig);
732 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
734 debug!("check_method_receiver: sig={:?}", sig);
736 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
737 let self_ty = fcx.tcx.liberate_late_bound_regions(
739 &ty::Binder::bind(self_ty)
742 let receiver_ty = sig.inputs()[0];
744 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
745 let receiver_ty = fcx.tcx.liberate_late_bound_regions(
747 &ty::Binder::bind(receiver_ty)
750 if fcx.tcx.features().arbitrary_self_types {
751 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
752 // report error, arbitrary_self_types was enabled
753 fcx.tcx.sess.diagnostic().mut_span_err(
754 span, &format!("invalid method receiver type: {:?}", receiver_ty)
755 ).note("type of `self` must be `Self` or a type that dereferences to it")
756 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
757 .code(DiagnosticId::Error("E0307".into()))
761 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
762 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
763 // report error, would have worked with arbitrary_self_types
764 feature_gate::feature_err(
765 &fcx.tcx.sess.parse_sess,
766 "arbitrary_self_types",
770 "`{}` cannot be used as the type of `self` without \
771 the `arbitrary_self_types` feature",
774 ).help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
777 // report error, would not have worked with arbitrary_self_types
778 fcx.tcx.sess.diagnostic().mut_span_err(
779 span, &format!("invalid method receiver type: {:?}", receiver_ty)
780 ).note("type must be `Self` or a type that dereferences to it")
781 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
782 .code(DiagnosticId::Error("E0307".into()))
789 /// returns true if `receiver_ty` would be considered a valid receiver type for `self_ty`. If
790 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
791 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
792 /// strict: `receiver_ty` must implement `Receiver` and directly implement `Deref<Target=self_ty>`.
794 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
795 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
796 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
797 fn receiver_is_valid<'fcx, 'tcx, 'gcx>(
798 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
800 receiver_ty: Ty<'tcx>,
802 arbitrary_self_types_enabled: bool,
804 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
806 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
808 // `self: Self` is always valid
809 if can_eq_self(receiver_ty) {
810 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
816 let mut autoderef = fcx.autoderef(span, receiver_ty);
818 // the `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`
819 if arbitrary_self_types_enabled {
820 autoderef = autoderef.include_raw_pointers();
823 // the first type is `receiver_ty`, which we know its not equal to `self_ty`. skip it.
826 // keep dereferencing `receiver_ty` until we get to `self_ty`
828 if let Some((potential_self_ty, _)) = autoderef.next() {
829 debug!("receiver_is_valid: potential self type `{:?}` to match `{:?}`",
830 potential_self_ty, self_ty);
832 if can_eq_self(potential_self_ty) {
833 autoderef.finalize(fcx);
835 if let Some(mut err) = fcx.demand_eqtype_with_origin(
836 &cause, self_ty, potential_self_ty
844 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`",
845 receiver_ty, self_ty);
849 // without the `arbitrary_self_types` feature, `receiver_ty` must directly deref to
850 // `self_ty`. Enforce this by only doing one iteration of the loop
851 if !arbitrary_self_types_enabled {
856 // without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`
857 if !arbitrary_self_types_enabled {
858 let trait_def_id = match fcx.tcx.lang_items().receiver_trait() {
861 debug!("receiver_is_valid: missing Receiver trait");
866 let trait_ref = ty::TraitRef{
867 def_id: trait_def_id,
868 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
871 let obligation = traits::Obligation::new(
874 trait_ref.to_predicate()
877 if !fcx.predicate_must_hold_modulo_regions(&obligation) {
878 debug!("receiver_is_valid: type `{:?}` does not implement `Receiver` trait",
887 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
889 hir_generics: &hir::Generics)
891 let item_def_id = tcx.hir().local_def_id(item.id);
892 let ty = tcx.type_of(item_def_id);
893 if tcx.has_error_field(ty) {
897 let ty_predicates = tcx.predicates_of(item_def_id);
898 assert_eq!(ty_predicates.parent, None);
899 let variances = tcx.variances_of(item_def_id);
901 let mut constrained_parameters: FxHashSet<_> =
902 variances.iter().enumerate()
903 .filter(|&(_, &variance)| variance != ty::Bivariant)
904 .map(|(index, _)| Parameter(index as u32))
907 identify_constrained_type_params(tcx,
910 &mut constrained_parameters);
912 for (index, _) in variances.iter().enumerate() {
913 if constrained_parameters.contains(&Parameter(index as u32)) {
917 let param = &hir_generics.params[index];
919 hir::ParamName::Error => { }
920 _ => report_bivariance(tcx, param.span, param.name.ident().name),
925 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
927 param_name: ast::Name)
929 let mut err = error_392(tcx, span, param_name);
931 let suggested_marker_id = tcx.lang_items().phantom_data();
932 // help is available only in presence of lang items
933 if let Some(def_id) = suggested_marker_id {
934 err.help(&format!("consider removing `{}` or using a marker such as `{}`",
936 tcx.item_path_str(def_id)));
941 fn reject_shadowing_parameters(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) {
942 let generics = tcx.generics_of(def_id);
943 let parent = tcx.generics_of(generics.parent.unwrap());
944 let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
945 GenericParamDefKind::Lifetime => None,
946 GenericParamDefKind::Type {..} => Some((param.name, param.def_id)),
949 for method_param in &generics.params {
950 // Shadowing is checked in resolve_lifetime.
951 if let GenericParamDefKind::Lifetime = method_param.kind {
954 if impl_params.contains_key(&method_param.name) {
955 // Tighten up the span to focus on only the shadowing type
956 let type_span = tcx.def_span(method_param.def_id);
958 // The expectation here is that the original trait declaration is
959 // local so it should be okay to just unwrap everything.
960 let trait_def_id = impl_params[&method_param.name];
961 let trait_decl_span = tcx.def_span(trait_def_id);
962 error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
967 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
969 fn check_false_global_bounds<'a, 'gcx, 'tcx>(
970 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
974 use rustc::ty::TypeFoldable;
976 let empty_env = ty::ParamEnv::empty();
978 let def_id = fcx.tcx.hir().local_def_id_from_hir_id(id);
979 let predicates = fcx.tcx.predicates_of(def_id).predicates
983 // Check elaborated bounds
984 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
986 for pred in implied_obligations {
987 // Match the existing behavior.
988 if pred.is_global() && !pred.has_late_bound_regions() {
989 let pred = fcx.normalize_associated_types_in(span, &pred);
990 let obligation = traits::Obligation::new(
991 traits::ObligationCause::new(
994 traits::TrivialBound,
999 fcx.register_predicate(obligation);
1003 fcx.select_all_obligations_or_error();
1006 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
1007 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1010 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
1011 pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
1012 -> CheckTypeWellFormedVisitor<'a, 'gcx> {
1013 CheckTypeWellFormedVisitor {
1019 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'a, 'tcx> {
1020 fn visit_item(&mut self, i: &'tcx hir::Item) {
1021 debug!("visit_item: {:?}", i);
1022 let def_id = self.tcx.hir().local_def_id(i.id);
1023 self.tcx.ensure().check_item_well_formed(def_id);
1026 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
1027 debug!("visit_trait_item: {:?}", trait_item);
1028 let def_id = self.tcx.hir().local_def_id(trait_item.id);
1029 self.tcx.ensure().check_trait_item_well_formed(def_id);
1032 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
1033 debug!("visit_impl_item: {:?}", impl_item);
1034 let def_id = self.tcx.hir().local_def_id(impl_item.id);
1035 self.tcx.ensure().check_impl_item_well_formed(def_id);
1039 ///////////////////////////////////////////////////////////////////////////
1042 struct AdtVariant<'tcx> {
1043 fields: Vec<AdtField<'tcx>>,
1046 struct AdtField<'tcx> {
1051 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1052 fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
1053 let fields = struct_def.fields().iter().map(|field| {
1054 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.id));
1055 let field_ty = self.normalize_associated_types_in(field.span,
1057 AdtField { ty: field_ty, span: field.span }
1060 AdtVariant { fields }
1063 fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
1064 enum_def.variants.iter()
1065 .map(|variant| self.non_enum_variant(&variant.node.data))
1069 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1070 match self.tcx.impl_trait_ref(impl_def_id) {
1071 Some(ref trait_ref) => {
1072 // Trait impl: take implied bounds from all types that
1073 // appear in the trait reference.
1074 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1075 trait_ref.substs.types().collect()
1079 // Inherent impl: take implied bounds from the `self` type.
1080 let self_ty = self.tcx.type_of(impl_def_id);
1081 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1088 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
1089 -> DiagnosticBuilder<'tcx> {
1090 let mut err = struct_span_err!(tcx.sess, span, E0392,
1091 "parameter `{}` is never used", param_name);
1092 err.span_label(span, "unused type parameter");
1096 fn error_194(tcx: TyCtxt<'_, '_, '_>, span: Span, trait_decl_span: Span, name: &str) {
1097 struct_span_err!(tcx.sess, span, E0194,
1098 "type parameter `{}` shadows another type parameter of the same name",
1100 .span_label(span, "shadows another type parameter")
1101 .span_label(trait_decl_span, format!("first `{}` declared here", name))