1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use check::{Inherited, FnCtxt};
12 use constrained_type_params::{identify_constrained_type_params, Parameter};
14 use hir::def_id::DefId;
15 use rustc::traits::{self, ObligationCauseCode};
16 use rustc::ty::{self, Lift, Ty, TyCtxt, TyKind, GenericParamDefKind, TypeFoldable, ToPredicate};
17 use rustc::ty::subst::{Subst, Substs};
18 use rustc::util::nodemap::{FxHashSet, FxHashMap};
19 use rustc::middle::lang_items;
20 use rustc::infer::opaque_types::may_define_existential_type;
23 use syntax::feature_gate::{self, GateIssue};
25 use errors::{DiagnosticBuilder, DiagnosticId};
27 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
30 /// Helper type of a temporary returned by `.for_item(...)`.
31 /// Necessary because we can't write the following bound:
32 /// `F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>)`.
33 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
34 inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
37 param_env: ty::ParamEnv<'tcx>,
40 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
41 fn with_fcx<F>(&'tcx mut self, f: F) where
42 F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
43 TyCtxt<'b, 'gcx, 'gcx>) -> Vec<Ty<'tcx>>
47 let param_env = self.param_env;
48 self.inherited.enter(|inh| {
49 let fcx = FnCtxt::new(&inh, param_env, id);
50 if !inh.tcx.features().trivial_bounds {
51 // As predicates are cached rather than obligations, this
52 // needsto be called first so that they are checked with an
54 check_false_global_bounds(&fcx, span, id);
56 let wf_tys = f(&fcx, fcx.tcx.global_tcx());
57 fcx.select_all_obligations_or_error();
58 fcx.regionck_item(id, span, &wf_tys);
63 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
64 /// well-formed, meaning that they do not require any constraints not declared in the struct
65 /// definition itself. For example, this definition would be illegal:
67 /// struct Ref<'a, T> { x: &'a T }
69 /// because the type did not declare that `T:'a`.
71 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
72 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
74 pub fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
75 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
76 let item = tcx.hir().expect_item(node_id);
78 debug!("check_item_well_formed(it.id={}, it.name={})",
80 tcx.item_path_str(def_id));
83 // Right now we check that every default trait implementation
84 // has an implementation of itself. Basically, a case like:
86 // `impl Trait for T {}`
88 // has a requirement of `T: Trait` which was required for default
89 // method implementations. Although this could be improved now that
90 // there's a better infrastructure in place for this, it's being left
91 // for a follow-up work.
93 // Since there's such a requirement, we need to check *just* positive
94 // implementations, otherwise things like:
96 // impl !Send for T {}
98 // won't be allowed unless there's an *explicit* implementation of `Send`
100 hir::ItemKind::Impl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
101 let is_auto = tcx.impl_trait_ref(tcx.hir().local_def_id(item.id))
102 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
103 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
104 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
106 if polarity == hir::ImplPolarity::Positive {
107 check_impl(tcx, item, self_ty, trait_ref);
109 // FIXME(#27579) what amount of WF checking do we need for neg impls?
110 if trait_ref.is_some() && !is_auto {
111 span_err!(tcx.sess, item.span, E0192,
112 "negative impls are only allowed for \
113 auto traits (e.g., `Send` and `Sync`)")
117 hir::ItemKind::Fn(..) => {
118 check_item_fn(tcx, item);
120 hir::ItemKind::Static(ref ty, ..) => {
121 check_item_type(tcx, item.id, ty.span, false);
123 hir::ItemKind::Const(ref ty, ..) => {
124 check_item_type(tcx, item.id, ty.span, false);
126 hir::ItemKind::ForeignMod(ref module) => for it in module.items.iter() {
127 if let hir::ForeignItemKind::Static(ref ty, ..) = it.node {
128 check_item_type(tcx, it.id, ty.span, true);
131 hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
132 check_type_defn(tcx, item, false, |fcx| {
133 vec![fcx.non_enum_variant(struct_def)]
136 check_variances_for_type_defn(tcx, item, ast_generics);
138 hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
139 check_type_defn(tcx, item, true, |fcx| {
140 vec![fcx.non_enum_variant(struct_def)]
143 check_variances_for_type_defn(tcx, item, ast_generics);
145 hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
146 check_type_defn(tcx, item, true, |fcx| {
147 fcx.enum_variants(enum_def)
150 check_variances_for_type_defn(tcx, item, ast_generics);
152 hir::ItemKind::Trait(..) => {
153 check_trait(tcx, item);
155 hir::ItemKind::TraitAlias(..) => {
156 check_trait(tcx, item);
162 pub fn check_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
163 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
164 let trait_item = tcx.hir().expect_trait_item(node_id);
166 let method_sig = match trait_item.node {
167 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
170 check_associated_item(tcx, trait_item.id, trait_item.span, method_sig);
173 pub fn check_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
174 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
175 let impl_item = tcx.hir().expect_impl_item(node_id);
177 let method_sig = match impl_item.node {
178 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
181 check_associated_item(tcx, impl_item.id, impl_item.span, method_sig);
184 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
185 item_id: ast::NodeId,
187 sig_if_method: Option<&hir::MethodSig>) {
188 debug!("check_associated_item: {:?}", item_id);
190 let code = ObligationCauseCode::MiscObligation;
191 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
192 let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
194 let (mut implied_bounds, self_ty) = match item.container {
195 ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
196 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
197 fcx.tcx.type_of(def_id))
201 ty::AssociatedKind::Const => {
202 let ty = fcx.tcx.type_of(item.def_id);
203 let ty = fcx.normalize_associated_types_in(span, &ty);
204 fcx.register_wf_obligation(ty, span, code.clone());
206 ty::AssociatedKind::Method => {
207 reject_shadowing_parameters(fcx.tcx, item.def_id);
208 let sig = fcx.tcx.fn_sig(item.def_id);
209 let sig = fcx.normalize_associated_types_in(span, &sig);
210 check_fn_or_method(tcx, fcx, span, sig,
211 item.def_id, &mut implied_bounds);
212 let sig_if_method = sig_if_method.expect("bad signature for method");
213 check_method_receiver(fcx, sig_if_method, &item, self_ty);
215 ty::AssociatedKind::Type => {
216 if item.defaultness.has_value() {
217 let ty = fcx.tcx.type_of(item.def_id);
218 let ty = fcx.normalize_associated_types_in(span, &ty);
219 fcx.register_wf_obligation(ty, span, code.clone());
222 ty::AssociatedKind::Existential => {
223 // do nothing, existential types check themselves
231 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
232 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
233 for_id(tcx, item.id, item.span)
236 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId, span: Span)
237 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
238 let def_id = tcx.hir().local_def_id(id);
240 inherited: Inherited::build(tcx, def_id),
243 param_env: tcx.param_env(def_id),
247 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
248 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
249 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
250 where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
252 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
253 let variants = lookup_fields(fcx);
254 let def_id = fcx.tcx.hir().local_def_id(item.id);
255 let packed = fcx.tcx.adt_def(def_id).repr.packed();
257 for variant in &variants {
258 // For DST, or when drop needs to copy things around, all
259 // intermediate types must be sized.
260 let needs_drop_copy = || {
262 let ty = variant.fields.last().unwrap().ty;
263 let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
265 span_bug!(item.span, "inference variables in {:?}", ty)
267 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
272 variant.fields.is_empty() ||
274 let unsized_len = if all_sized {
279 for (idx, field) in variant.fields[..variant.fields.len() - unsized_len]
283 let last = idx == variant.fields.len() - 1;
286 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
287 traits::ObligationCause::new(
291 adt_kind: match item.node.adt_kind() {
301 // All field types must be well-formed.
302 for field in &variant.fields {
303 fcx.register_wf_obligation(field.ty, field.span,
304 ObligationCauseCode::MiscObligation)
308 check_where_clauses(tcx, fcx, item.span, def_id, None);
310 vec![] // no implied bounds in a struct def'n
314 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
315 debug!("check_trait: {:?}", item.id);
317 let trait_def_id = tcx.hir().local_def_id(item.id);
319 let trait_def = tcx.trait_def(trait_def_id);
320 if trait_def.is_marker {
321 for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
324 tcx.def_span(*associated_def_id),
326 "marker traits cannot have associated items",
331 for_item(tcx, item).with_fcx(|fcx, _| {
332 check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
337 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
338 for_item(tcx, item).with_fcx(|fcx, tcx| {
339 let def_id = fcx.tcx.hir().local_def_id(item.id);
340 let sig = fcx.tcx.fn_sig(def_id);
341 let sig = fcx.normalize_associated_types_in(item.span, &sig);
342 let mut implied_bounds = vec![];
343 check_fn_or_method(tcx, fcx, item.span, sig,
344 def_id, &mut implied_bounds);
349 fn check_item_type<'a, 'tcx>(
350 tcx: TyCtxt<'a, 'tcx, 'tcx>,
351 item_id: ast::NodeId,
353 allow_foreign_ty: bool,
355 debug!("check_item_type: {:?}", item_id);
357 for_id(tcx, item_id, ty_span).with_fcx(|fcx, gcx| {
358 let ty = gcx.type_of(gcx.hir().local_def_id(item_id));
359 let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
361 let mut forbid_unsized = true;
362 if allow_foreign_ty {
363 if let TyKind::Foreign(_) = fcx.tcx.struct_tail(item_ty).sty {
364 forbid_unsized = false;
368 fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
372 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
373 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
377 vec![] // no implied bounds in a const etc
381 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
383 ast_self_ty: &hir::Ty,
384 ast_trait_ref: &Option<hir::TraitRef>)
386 debug!("check_impl: {:?}", item);
388 for_item(tcx, item).with_fcx(|fcx, tcx| {
389 let item_def_id = fcx.tcx.hir().local_def_id(item.id);
391 match *ast_trait_ref {
392 Some(ref ast_trait_ref) => {
393 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
395 fcx.normalize_associated_types_in(
396 ast_trait_ref.path.span, &trait_ref);
398 ty::wf::trait_obligations(fcx,
402 ast_trait_ref.path.span);
403 for obligation in obligations {
404 fcx.register_predicate(obligation);
408 let self_ty = fcx.tcx.type_of(item_def_id);
409 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
410 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
411 ObligationCauseCode::MiscObligation);
415 check_where_clauses(tcx, fcx, item.span, item_def_id, None);
417 fcx.impl_implied_bounds(item_def_id, item.span)
421 /// Checks where clauses and inline bounds that are declared on def_id.
422 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
423 tcx: TyCtxt<'a, 'gcx, 'gcx>,
424 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
427 return_ty: Option<Ty<'tcx>>,
429 use ty::subst::Subst;
430 use rustc::ty::TypeFoldable;
432 let predicates = fcx.tcx.predicates_of(def_id);
434 let generics = tcx.generics_of(def_id);
435 let is_our_default = |def: &ty::GenericParamDef| {
437 GenericParamDefKind::Type { has_default, .. } => {
438 has_default && def.index >= generics.parent_count as u32
444 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
445 // For example this forbids the declaration:
446 // struct Foo<T = Vec<[u32]>> { .. }
447 // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
448 for param in &generics.params {
449 if let GenericParamDefKind::Type {..} = param.kind {
450 if is_our_default(¶m) {
451 let ty = fcx.tcx.type_of(param.def_id);
452 // ignore dependent defaults -- that is, where the default of one type
453 // parameter includes another (e.g., <T, U = T>). In those cases, we can't
454 // be sure if it will error or not as user might always specify the other.
455 if !ty.needs_subst() {
456 fcx.register_wf_obligation(ty, fcx.tcx.def_span(param.def_id),
457 ObligationCauseCode::MiscObligation);
463 // Check that trait predicates are WF when params are substituted by their defaults.
464 // We don't want to overly constrain the predicates that may be written but we want to
465 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
466 // Therefore we check if a predicate which contains a single type param
467 // with a concrete default is WF with that default substituted.
468 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
470 // First we build the defaulted substitution.
471 let substs = Substs::for_item(fcx.tcx, def_id, |param, _| {
473 GenericParamDefKind::Lifetime => {
474 // All regions are identity.
475 fcx.tcx.mk_param_from_def(param)
477 GenericParamDefKind::Type {..} => {
478 // If the param has a default,
479 if is_our_default(param) {
480 let default_ty = fcx.tcx.type_of(param.def_id);
481 // and it's not a dependent default
482 if !default_ty.needs_subst() {
483 // then substitute with the default.
484 return default_ty.into();
487 // Mark unwanted params as err.
488 fcx.tcx.types.err.into()
492 // Now we build the substituted predicates.
493 let default_obligations = predicates.predicates.iter().flat_map(|&(pred, _)| {
495 struct CountParams { params: FxHashSet<u32> }
496 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
497 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
500 self.params.insert(p.idx);
501 t.super_visit_with(self)
503 _ => t.super_visit_with(self)
507 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
511 let mut param_count = CountParams::default();
512 let has_region = pred.visit_with(&mut param_count);
513 let substituted_pred = pred.subst(fcx.tcx, substs);
514 // Don't check non-defaulted params, dependent defaults (including lifetimes)
515 // or preds with multiple params.
516 if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
518 } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
519 // Avoid duplication of predicates that contain no parameters, for example.
522 Some(substituted_pred)
525 // convert each of those into an obligation. So if you have
526 // something like `struct Foo<T: Copy = String>`, we would
527 // take that predicate `T: Copy`, substitute to `String: Copy`
528 // (actually that happens in the previous `flat_map` call),
529 // and then try to prove it (in this case, we'll fail).
531 // Note the subtle difference from how we handle `predicates`
532 // below: there, we are not trying to prove those predicates
533 // to be *true* but merely *well-formed*.
534 let pred = fcx.normalize_associated_types_in(span, &pred);
535 let cause = traits::ObligationCause::new(span, fcx.body_id, traits::ItemObligation(def_id));
536 traits::Obligation::new(cause, fcx.param_env, pred)
539 let mut predicates = predicates.instantiate_identity(fcx.tcx);
541 if let Some(return_ty) = return_ty {
542 predicates.predicates.extend(check_existential_types(tcx, fcx, def_id, span, return_ty));
545 let predicates = fcx.normalize_associated_types_in(span, &predicates);
547 debug!("check_where_clauses: predicates={:?}", predicates.predicates);
549 predicates.predicates
551 .flat_map(|p| ty::wf::predicate_obligations(fcx,
557 for obligation in wf_obligations.chain(default_obligations) {
558 debug!("next obligation cause: {:?}", obligation.cause);
559 fcx.register_predicate(obligation);
563 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
564 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
566 sig: ty::PolyFnSig<'tcx>,
568 implied_bounds: &mut Vec<Ty<'tcx>>)
570 let sig = fcx.normalize_associated_types_in(span, &sig);
571 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
573 for input_ty in sig.inputs() {
574 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
576 implied_bounds.extend(sig.inputs());
578 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
580 // FIXME(#25759) return types should not be implied bounds
581 implied_bounds.push(sig.output());
583 check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
586 /// Checks "defining uses" of existential types to ensure that they meet the restrictions laid for
587 /// "higher-order pattern unification".
588 /// This ensures that inference is tractable.
589 /// In particular, definitions of existential types can only use other generics as arguments,
590 /// and they cannot repeat an argument. Example:
593 /// existential type Foo<A, B>;
595 /// // ok -- `Foo` is applied to two distinct, generic types.
596 /// fn a<T, U>() -> Foo<T, U> { .. }
598 /// // not ok -- `Foo` is applied to `T` twice.
599 /// fn b<T>() -> Foo<T, T> { .. }
602 /// // not ok -- `Foo` is applied to a non-generic type.
603 /// fn b<T>() -> Foo<T, u32> { .. }
606 fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>(
607 tcx: TyCtxt<'a, 'gcx, 'gcx>,
608 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
612 ) -> Vec<ty::Predicate<'tcx>> {
613 trace!("check_existential_types: {:?}, {:?}", ty, ty.sty);
614 let mut substituted_predicates = Vec::new();
615 ty.fold_with(&mut ty::fold::BottomUpFolder {
618 if let ty::Opaque(def_id, substs) = ty.sty {
619 trace!("check_existential_types: opaque_ty, {:?}, {:?}", def_id, substs);
620 let generics = tcx.generics_of(def_id);
621 // only check named existential types
622 if generics.parent.is_none() {
623 let opaque_node_id = tcx.hir().as_local_node_id(def_id).unwrap();
624 if may_define_existential_type(tcx, fn_def_id, opaque_node_id) {
625 trace!("check_existential_types may define. Generics: {:#?}", generics);
626 let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
627 for (subst, param) in substs.iter().zip(&generics.params) {
628 match subst.unpack() {
629 ty::subst::UnpackedKind::Type(ty) => match ty.sty {
631 // prevent `fn foo() -> Foo<u32>` from being defining
637 "non-defining existential type use \
641 tcx.def_span(param.def_id),
643 "used non-generic type {} for \
651 ty::subst::UnpackedKind::Lifetime(region) => {
652 let param_span = tcx.def_span(param.def_id);
653 if let ty::ReStatic = region {
658 "non-defining existential type use \
663 "cannot use static lifetime, use a bound lifetime \
664 instead or remove the lifetime parameter from the \
669 seen.entry(region).or_default().push(param_span);
673 } // for (subst, param)
674 for (_, spans) in seen {
680 "non-defining existential type use \
685 "lifetime used multiple times",
690 } // if may_define_existential_type
692 // now register the bounds on the parameters of the existential type
693 // so the parameters given by the function need to fulfill them
695 // existential type Foo<T: Bar>: 'static;
696 // fn foo<U>() -> Foo<U> { .. *}
700 // existential type Foo<T: Bar>: 'static;
701 // fn foo<U: Bar>() -> Foo<U> { .. *}
703 let predicates = tcx.predicates_of(def_id);
705 "check_existential_types may define. adding predicates: {:#?}",
708 for &(pred, _) in predicates.predicates.iter() {
709 let substituted_pred = pred.subst(fcx.tcx, substs);
710 // Avoid duplication of predicates that contain no parameters, for example.
711 if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
712 substituted_predicates.push(substituted_pred);
715 } // if is_named_existential_type
721 substituted_predicates
724 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
725 method_sig: &hir::MethodSig,
726 method: &ty::AssociatedItem,
729 // check that the method has a valid receiver type, given the type `Self`
730 debug!("check_method_receiver({:?}, self_ty={:?})",
733 if !method.method_has_self_argument {
737 let span = method_sig.decl.inputs[0].span;
739 let sig = fcx.tcx.fn_sig(method.def_id);
740 let sig = fcx.normalize_associated_types_in(span, &sig);
741 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
743 debug!("check_method_receiver: sig={:?}", sig);
745 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
746 let self_ty = fcx.tcx.liberate_late_bound_regions(
748 &ty::Binder::bind(self_ty)
751 let receiver_ty = sig.inputs()[0];
753 let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
754 let receiver_ty = fcx.tcx.liberate_late_bound_regions(
756 &ty::Binder::bind(receiver_ty)
759 if fcx.tcx.features().arbitrary_self_types {
760 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
761 // report error, arbitrary_self_types was enabled
762 fcx.tcx.sess.diagnostic().mut_span_err(
763 span, &format!("invalid method receiver type: {:?}", receiver_ty)
764 ).note("type of `self` must be `Self` or a type that dereferences to it")
765 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
766 .code(DiagnosticId::Error("E0307".into()))
770 if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
771 if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
772 // report error, would have worked with arbitrary_self_types
773 feature_gate::feature_err(
774 &fcx.tcx.sess.parse_sess,
775 "arbitrary_self_types",
779 "`{}` cannot be used as the type of `self` without \
780 the `arbitrary_self_types` feature",
783 ).help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
786 // report error, would not have worked with arbitrary_self_types
787 fcx.tcx.sess.diagnostic().mut_span_err(
788 span, &format!("invalid method receiver type: {:?}", receiver_ty)
789 ).note("type 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()))
798 /// returns true if `receiver_ty` would be considered a valid receiver type for `self_ty`. If
799 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
800 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
801 /// strict: `receiver_ty` must implement `Receiver` and directly implement `Deref<Target=self_ty>`.
803 /// NB: there are cases this function returns `true` but causes an error to be emitted,
804 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
805 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
806 fn receiver_is_valid<'fcx, 'tcx, 'gcx>(
807 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
809 receiver_ty: Ty<'tcx>,
811 arbitrary_self_types_enabled: bool,
813 let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
815 let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
817 // `self: Self` is always valid
818 if can_eq_self(receiver_ty) {
819 if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
825 let mut autoderef = fcx.autoderef(span, receiver_ty);
827 // the `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`
828 if arbitrary_self_types_enabled {
829 autoderef = autoderef.include_raw_pointers();
832 // the first type is `receiver_ty`, which we know its not equal to `self_ty`. skip it.
835 // keep dereferencing `receiver_ty` until we get to `self_ty`
837 if let Some((potential_self_ty, _)) = autoderef.next() {
838 debug!("receiver_is_valid: potential self type `{:?}` to match `{:?}`",
839 potential_self_ty, self_ty);
841 if can_eq_self(potential_self_ty) {
842 autoderef.finalize(fcx);
844 if let Some(mut err) = fcx.demand_eqtype_with_origin(
845 &cause, self_ty, potential_self_ty
853 debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`",
854 receiver_ty, self_ty);
858 // without the `arbitrary_self_types` feature, `receiver_ty` must directly deref to
859 // `self_ty`. Enforce this by only doing one iteration of the loop
860 if !arbitrary_self_types_enabled {
865 // without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`
866 if !arbitrary_self_types_enabled {
867 let trait_def_id = match fcx.tcx.lang_items().receiver_trait() {
870 debug!("receiver_is_valid: missing Receiver trait");
875 let trait_ref = ty::TraitRef{
876 def_id: trait_def_id,
877 substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
880 let obligation = traits::Obligation::new(
883 trait_ref.to_predicate()
886 if !fcx.predicate_must_hold(&obligation) {
887 debug!("receiver_is_valid: type `{:?}` does not implement `Receiver` trait",
896 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
898 hir_generics: &hir::Generics)
900 let item_def_id = tcx.hir().local_def_id(item.id);
901 let ty = tcx.type_of(item_def_id);
902 if tcx.has_error_field(ty) {
906 let ty_predicates = tcx.predicates_of(item_def_id);
907 assert_eq!(ty_predicates.parent, None);
908 let variances = tcx.variances_of(item_def_id);
910 let mut constrained_parameters: FxHashSet<_> =
911 variances.iter().enumerate()
912 .filter(|&(_, &variance)| variance != ty::Bivariant)
913 .map(|(index, _)| Parameter(index as u32))
916 identify_constrained_type_params(tcx,
919 &mut constrained_parameters);
921 for (index, _) in variances.iter().enumerate() {
922 if constrained_parameters.contains(&Parameter(index as u32)) {
926 let param = &hir_generics.params[index];
928 hir::ParamName::Error => { }
929 _ => report_bivariance(tcx, param.span, param.name.ident().name),
934 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
936 param_name: ast::Name)
938 let mut err = error_392(tcx, span, param_name);
940 let suggested_marker_id = tcx.lang_items().phantom_data();
941 // help is available only in presence of lang items
942 if let Some(def_id) = suggested_marker_id {
943 err.help(&format!("consider removing `{}` or using a marker such as `{}`",
945 tcx.item_path_str(def_id)));
950 fn reject_shadowing_parameters(tcx: TyCtxt, def_id: DefId) {
951 let generics = tcx.generics_of(def_id);
952 let parent = tcx.generics_of(generics.parent.unwrap());
953 let impl_params: FxHashMap<_, _> = parent.params.iter().flat_map(|param| match param.kind {
954 GenericParamDefKind::Lifetime => None,
955 GenericParamDefKind::Type {..} => Some((param.name, param.def_id)),
958 for method_param in &generics.params {
959 // Shadowing is checked in resolve_lifetime.
960 if let GenericParamDefKind::Lifetime = method_param.kind {
963 if impl_params.contains_key(&method_param.name) {
964 // Tighten up the span to focus on only the shadowing type
965 let type_span = tcx.def_span(method_param.def_id);
967 // The expectation here is that the original trait declaration is
968 // local so it should be okay to just unwrap everything.
969 let trait_def_id = impl_params[&method_param.name];
970 let trait_decl_span = tcx.def_span(trait_def_id);
971 error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
976 /// Feature gates RFC 2056 - trivial bounds, checking for global bounds that
978 fn check_false_global_bounds<'a, 'gcx, 'tcx>(
979 fcx: &FnCtxt<'a, 'gcx, 'tcx>,
983 use rustc::ty::TypeFoldable;
985 let empty_env = ty::ParamEnv::empty();
987 let def_id = fcx.tcx.hir().local_def_id(id);
988 let predicates = fcx.tcx.predicates_of(def_id).predicates
992 // Check elaborated bounds
993 let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
995 for pred in implied_obligations {
996 // Match the existing behavior.
997 if pred.is_global() && !pred.has_late_bound_regions() {
998 let pred = fcx.normalize_associated_types_in(span, &pred);
999 let obligation = traits::Obligation::new(
1000 traits::ObligationCause::new(
1003 traits::TrivialBound,
1008 fcx.register_predicate(obligation);
1012 fcx.select_all_obligations_or_error();
1015 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
1016 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1019 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
1020 pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
1021 -> CheckTypeWellFormedVisitor<'a, 'gcx> {
1022 CheckTypeWellFormedVisitor {
1028 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
1029 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1030 NestedVisitorMap::None
1033 fn visit_item(&mut self, i: &hir::Item) {
1034 debug!("visit_item: {:?}", i);
1035 let def_id = self.tcx.hir().local_def_id(i.id);
1036 ty::query::queries::check_item_well_formed::ensure(self.tcx, def_id);
1037 intravisit::walk_item(self, i);
1040 fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
1041 debug!("visit_trait_item: {:?}", trait_item);
1042 let def_id = self.tcx.hir().local_def_id(trait_item.id);
1043 ty::query::queries::check_trait_item_well_formed::ensure(self.tcx, def_id);
1044 intravisit::walk_trait_item(self, trait_item)
1047 fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
1048 debug!("visit_impl_item: {:?}", impl_item);
1049 let def_id = self.tcx.hir().local_def_id(impl_item.id);
1050 ty::query::queries::check_impl_item_well_formed::ensure(self.tcx, def_id);
1051 intravisit::walk_impl_item(self, impl_item)
1055 ///////////////////////////////////////////////////////////////////////////
1058 struct AdtVariant<'tcx> {
1059 fields: Vec<AdtField<'tcx>>,
1062 struct AdtField<'tcx> {
1067 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1068 fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
1069 let fields = struct_def.fields().iter().map(|field| {
1070 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.id));
1071 let field_ty = self.normalize_associated_types_in(field.span,
1073 AdtField { ty: field_ty, span: field.span }
1076 AdtVariant { fields }
1079 fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
1080 enum_def.variants.iter()
1081 .map(|variant| self.non_enum_variant(&variant.node.data))
1085 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1086 match self.tcx.impl_trait_ref(impl_def_id) {
1087 Some(ref trait_ref) => {
1088 // Trait impl: take implied bounds from all types that
1089 // appear in the trait reference.
1090 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1091 trait_ref.substs.types().collect()
1095 // Inherent impl: take implied bounds from the `self` type.
1096 let self_ty = self.tcx.type_of(impl_def_id);
1097 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1104 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
1105 -> DiagnosticBuilder<'tcx> {
1106 let mut err = struct_span_err!(tcx.sess, span, E0392,
1107 "parameter `{}` is never used", param_name);
1108 err.span_label(span, "unused type parameter");
1112 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: &str) {
1113 struct_span_err!(tcx.sess, span, E0194,
1114 "type parameter `{}` shadows another type parameter of the same name",
1116 .span_label(span, "shadows another type parameter")
1117 .span_label(trait_decl_span, format!("first `{}` declared here", name))