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};
17 use rustc::ty::util::ExplicitSelf;
18 use rustc::util::nodemap::{FxHashSet, FxHashMap};
19 use rustc::middle::lang_items;
22 use syntax::feature_gate::{self, GateIssue};
24 use errors::{DiagnosticBuilder, DiagnosticId};
26 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
29 /// Helper type of a temporary returned by .for_item(...).
30 /// Necessary because we can't write the following bound:
31 /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(FnCtxt<'b, 'gcx, 'tcx>).
32 struct CheckWfFcxBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
33 inherited: super::InheritedBuilder<'a, 'gcx, 'tcx>,
36 param_env: ty::ParamEnv<'tcx>,
39 impl<'a, 'gcx, 'tcx> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
40 fn with_fcx<F>(&'tcx mut self, f: F) where
41 F: for<'b> FnOnce(&FnCtxt<'b, 'gcx, 'tcx>,
42 TyCtxt<'b, 'gcx, 'gcx>) -> Vec<Ty<'tcx>>
46 let param_env = self.param_env;
47 self.inherited.enter(|inh| {
48 let fcx = FnCtxt::new(&inh, param_env, id);
49 let wf_tys = f(&fcx, fcx.tcx.global_tcx());
50 fcx.select_all_obligations_or_error();
51 fcx.regionck_item(id, span, &wf_tys);
56 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
57 /// well-formed, meaning that they do not require any constraints not declared in the struct
58 /// definition itself. For example, this definition would be illegal:
60 /// struct Ref<'a, T> { x: &'a T }
62 /// because the type did not declare that `T:'a`.
64 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
65 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
67 pub fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
68 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
69 let item = tcx.hir.expect_item(node_id);
71 debug!("check_item_well_formed(it.id={}, it.name={})",
73 tcx.item_path_str(def_id));
76 // Right now we check that every default trait implementation
77 // has an implementation of itself. Basically, a case like:
79 // `impl Trait for T {}`
81 // has a requirement of `T: Trait` which was required for default
82 // method implementations. Although this could be improved now that
83 // there's a better infrastructure in place for this, it's being left
84 // for a follow-up work.
86 // Since there's such a requirement, we need to check *just* positive
87 // implementations, otherwise things like:
89 // impl !Send for T {}
91 // won't be allowed unless there's an *explicit* implementation of `Send`
93 hir::ItemImpl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
94 let is_auto = tcx.impl_trait_ref(tcx.hir.local_def_id(item.id))
95 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
96 if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
97 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
99 if polarity == hir::ImplPolarity::Positive {
100 check_impl(tcx, item, self_ty, trait_ref);
102 // FIXME(#27579) what amount of WF checking do we need for neg impls?
103 if trait_ref.is_some() && !is_auto {
104 span_err!(tcx.sess, item.span, E0192,
105 "negative impls are only allowed for \
106 auto traits (e.g., `Send` and `Sync`)")
111 check_item_fn(tcx, item);
113 hir::ItemStatic(..) => {
114 check_item_type(tcx, item);
116 hir::ItemConst(..) => {
117 check_item_type(tcx, item);
119 hir::ItemStruct(ref struct_def, ref ast_generics) => {
120 check_type_defn(tcx, item, false, |fcx| {
121 vec![fcx.non_enum_variant(struct_def)]
124 check_variances_for_type_defn(tcx, item, ast_generics);
126 hir::ItemUnion(ref struct_def, ref ast_generics) => {
127 check_type_defn(tcx, item, true, |fcx| {
128 vec![fcx.non_enum_variant(struct_def)]
131 check_variances_for_type_defn(tcx, item, ast_generics);
133 hir::ItemEnum(ref enum_def, ref ast_generics) => {
134 check_type_defn(tcx, item, true, |fcx| {
135 fcx.enum_variants(enum_def)
138 check_variances_for_type_defn(tcx, item, ast_generics);
140 hir::ItemTrait(..) => {
141 check_trait(tcx, item);
147 pub fn check_trait_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
148 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
149 let trait_item = tcx.hir.expect_trait_item(node_id);
151 let method_sig = match trait_item.node {
152 hir::TraitItemKind::Method(ref sig, _) => Some(sig),
155 check_associated_item(tcx, trait_item.id, trait_item.span, method_sig);
158 pub fn check_impl_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
159 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
160 let impl_item = tcx.hir.expect_impl_item(node_id);
162 let method_sig = match impl_item.node {
163 hir::ImplItemKind::Method(ref sig, _) => Some(sig),
166 check_associated_item(tcx, impl_item.id, impl_item.span, method_sig);
169 fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
170 item_id: ast::NodeId,
172 sig_if_method: Option<&hir::MethodSig>) {
173 let code = ObligationCauseCode::MiscObligation;
174 for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
175 let item = fcx.tcx.associated_item(fcx.tcx.hir.local_def_id(item_id));
177 let (mut implied_bounds, self_ty) = match item.container {
178 ty::TraitContainer(_) => (vec![], fcx.tcx.mk_self_type()),
179 ty::ImplContainer(def_id) => (fcx.impl_implied_bounds(def_id, span),
180 fcx.tcx.type_of(def_id))
184 ty::AssociatedKind::Const => {
185 let ty = fcx.tcx.type_of(item.def_id);
186 let ty = fcx.normalize_associated_types_in(span, &ty);
187 fcx.register_wf_obligation(ty, span, code.clone());
189 ty::AssociatedKind::Method => {
190 reject_shadowing_type_parameters(fcx.tcx, item.def_id);
191 let sig = fcx.tcx.fn_sig(item.def_id);
192 let sig = fcx.normalize_associated_types_in(span, &sig);
193 check_fn_or_method(tcx, fcx, span, sig,
194 item.def_id, &mut implied_bounds);
195 let sig_if_method = sig_if_method.expect("bad signature for method");
196 check_method_receiver(fcx, sig_if_method, &item, self_ty);
198 ty::AssociatedKind::Type => {
199 if item.defaultness.has_value() {
200 let ty = fcx.tcx.type_of(item.def_id);
201 let ty = fcx.normalize_associated_types_in(span, &ty);
202 fcx.register_wf_obligation(ty, span, code.clone());
211 fn for_item<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, item: &hir::Item)
212 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
213 for_id(tcx, item.id, item.span)
216 fn for_id<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>, id: ast::NodeId, span: Span)
217 -> CheckWfFcxBuilder<'a, 'gcx, 'tcx> {
218 let def_id = tcx.hir.local_def_id(id);
220 inherited: Inherited::build(tcx, def_id),
223 param_env: tcx.param_env(def_id),
227 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
228 fn check_type_defn<'a, 'tcx, F>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
229 item: &hir::Item, all_sized: bool, mut lookup_fields: F)
230 where F: for<'fcx, 'gcx, 'tcx2> FnMut(&FnCtxt<'fcx, 'gcx, 'tcx2>) -> Vec<AdtVariant<'tcx2>>
232 for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
233 let variants = lookup_fields(fcx);
234 let def_id = fcx.tcx.hir.local_def_id(item.id);
235 let packed = fcx.tcx.adt_def(def_id).repr.packed();
237 for variant in &variants {
238 // For DST, or when drop needs to copy things around, all
239 // intermediate types must be sized.
240 let needs_drop_copy = || {
242 let ty = variant.fields.last().unwrap().ty;
243 let ty = fcx.tcx.erase_regions(&ty).lift_to_tcx(fcx_tcx)
245 span_bug!(item.span, "inference variables in {:?}", ty)
247 ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
252 variant.fields.is_empty() ||
259 for field in &variant.fields[..variant.fields.len() - unsized_len] {
262 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
263 traits::ObligationCause::new(field.span,
265 traits::FieldSized(match item.node.adt_kind() {
271 // All field types must be well-formed.
272 for field in &variant.fields {
273 fcx.register_wf_obligation(field.ty, field.span,
274 ObligationCauseCode::MiscObligation)
278 check_where_clauses(tcx, fcx, item.span, def_id);
280 vec![] // no implied bounds in a struct def'n
284 fn check_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
285 let trait_def_id = tcx.hir.local_def_id(item.id);
286 for_item(tcx, item).with_fcx(|fcx, _| {
287 check_where_clauses(tcx, fcx, item.span, trait_def_id);
292 fn check_item_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &hir::Item) {
293 for_item(tcx, item).with_fcx(|fcx, tcx| {
294 let def_id = fcx.tcx.hir.local_def_id(item.id);
295 let sig = fcx.tcx.fn_sig(def_id);
296 let sig = fcx.normalize_associated_types_in(item.span, &sig);
297 let mut implied_bounds = vec![];
298 check_fn_or_method(tcx, fcx, item.span, sig,
299 def_id, &mut implied_bounds);
304 fn check_item_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
307 debug!("check_item_type: {:?}", item);
309 for_item(tcx, item).with_fcx(|fcx, _this| {
310 let ty = fcx.tcx.type_of(fcx.tcx.hir.local_def_id(item.id));
311 let item_ty = fcx.normalize_associated_types_in(item.span, &ty);
313 fcx.register_wf_obligation(item_ty, item.span, ObligationCauseCode::MiscObligation);
315 vec![] // no implied bounds in a const etc
319 fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
321 ast_self_ty: &hir::Ty,
322 ast_trait_ref: &Option<hir::TraitRef>)
324 debug!("check_impl: {:?}", item);
326 for_item(tcx, item).with_fcx(|fcx, tcx| {
327 let item_def_id = fcx.tcx.hir.local_def_id(item.id);
329 match *ast_trait_ref {
330 Some(ref ast_trait_ref) => {
331 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
333 fcx.normalize_associated_types_in(
334 ast_trait_ref.path.span, &trait_ref);
336 ty::wf::trait_obligations(fcx,
340 ast_trait_ref.path.span);
341 for obligation in obligations {
342 fcx.register_predicate(obligation);
346 let self_ty = fcx.tcx.type_of(item_def_id);
347 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
348 fcx.register_wf_obligation(self_ty, ast_self_ty.span,
349 ObligationCauseCode::MiscObligation);
353 check_where_clauses(tcx, fcx, item.span, item_def_id);
355 fcx.impl_implied_bounds(item_def_id, item.span)
359 /// Checks where clauses and inline bounds that are declared on def_id.
360 fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
361 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
364 use ty::subst::Subst;
365 use rustc::ty::TypeFoldable;
367 let mut predicates = fcx.tcx.predicates_of(def_id);
368 let mut substituted_predicates = Vec::new();
370 let generics = tcx.generics_of(def_id);
371 let is_our_default = |def: &ty::TypeParameterDef|
372 def.has_default && def.index >= generics.parent_count() as u32;
374 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
375 // For example this forbids the declaration:
376 // struct Foo<T = Vec<[u32]>> { .. }
377 // Here the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
378 for d in generics.types.iter().cloned().filter(is_our_default).map(|p| p.def_id) {
379 let ty = fcx.tcx.type_of(d);
380 // ignore dependent defaults -- that is, where the default of one type
381 // parameter includes another (e.g., <T, U = T>). In those cases, we can't
382 // be sure if it will error or not as user might always specify the other.
383 if !ty.needs_subst() {
384 fcx.register_wf_obligation(ty, fcx.tcx.def_span(d),
385 ObligationCauseCode::MiscObligation);
389 // Check that trait predicates are WF when params are substituted by their defaults.
390 // We don't want to overly constrain the predicates that may be written but we want to
391 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
392 // Therefore we check if a predicate which contains a single type param
393 // with a concrete default is WF with that default substituted.
394 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
396 // First we build the defaulted substitution.
397 let substs = ty::subst::Substs::for_item(fcx.tcx, def_id, |def, _| {
398 // All regions are identity.
399 fcx.tcx.mk_region(ty::ReEarlyBound(def.to_early_bound_region_data()))
401 // If the param has a default,
402 if is_our_default(def) {
403 let default_ty = fcx.tcx.type_of(def.def_id);
404 // and it's not a dependent default
405 if !default_ty.needs_subst() {
406 // then substitute with the default.
410 // Mark unwanted params as err.
413 // Now we build the substituted predicates.
414 for &pred in predicates.predicates.iter() {
415 struct CountParams { params: FxHashSet<u32> }
416 impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
417 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
420 self.params.insert(p.idx);
421 t.super_visit_with(self)
423 _ => t.super_visit_with(self)
427 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
431 let mut param_count = CountParams { params: FxHashSet() };
432 let has_region = pred.visit_with(&mut param_count);
433 let substituted_pred = pred.subst(fcx.tcx, substs);
434 // Don't check non-defaulted params, dependent defaults (including lifetimes)
435 // or preds with multiple params.
436 if substituted_pred.references_error() || param_count.params.len() > 1
440 // Avoid duplication of predicates that contain no parameters, for example.
441 if !predicates.predicates.contains(&substituted_pred) {
442 substituted_predicates.push(substituted_pred);
446 predicates.predicates.extend(substituted_predicates);
447 let predicates = predicates.instantiate_identity(fcx.tcx);
448 let predicates = fcx.normalize_associated_types_in(span, &predicates);
451 predicates.predicates
453 .flat_map(|p| ty::wf::predicate_obligations(fcx,
459 for obligation in obligations {
460 fcx.register_predicate(obligation);
464 fn check_fn_or_method<'a, 'fcx, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
465 fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
467 sig: ty::PolyFnSig<'tcx>,
469 implied_bounds: &mut Vec<Ty<'tcx>>)
471 let sig = fcx.normalize_associated_types_in(span, &sig);
472 let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
474 for input_ty in sig.inputs() {
475 fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
477 implied_bounds.extend(sig.inputs());
479 fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::MiscObligation);
481 // FIXME(#25759) return types should not be implied bounds
482 implied_bounds.push(sig.output());
484 check_where_clauses(tcx, fcx, span, def_id);
487 fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>,
488 method_sig: &hir::MethodSig,
489 method: &ty::AssociatedItem,
492 // check that the method has a valid receiver type, given the type `Self`
493 debug!("check_method_receiver({:?}, self_ty={:?})",
496 if !method.method_has_self_argument {
500 let span = method_sig.decl.inputs[0].span;
502 let sig = fcx.tcx.fn_sig(method.def_id);
503 let sig = fcx.normalize_associated_types_in(span, &sig);
504 let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
506 debug!("check_method_receiver: sig={:?}", sig);
508 let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
509 let self_ty = fcx.tcx.liberate_late_bound_regions(
511 &ty::Binder::bind(self_ty)
514 let self_arg_ty = sig.inputs()[0];
516 let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver);
517 let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty);
518 let self_arg_ty = fcx.tcx.liberate_late_bound_regions(
520 &ty::Binder::bind(self_arg_ty)
523 let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers();
526 if let Some((potential_self_ty, _)) = autoderef.next() {
527 debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`",
528 potential_self_ty, self_ty);
530 if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() {
531 autoderef.finalize();
532 if let Some(mut err) = fcx.demand_eqtype_with_origin(
533 &cause, self_ty, potential_self_ty) {
539 fcx.tcx.sess.diagnostic().mut_span_err(
540 span, &format!("invalid `self` type: {:?}", self_arg_ty))
541 .note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty))
542 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
543 .code(DiagnosticId::Error("E0307".into()))
549 let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
550 let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty);
552 if !fcx.tcx.features().arbitrary_self_types {
554 ExplicitSelf::ByValue |
555 ExplicitSelf::ByReference(_, _) |
556 ExplicitSelf::ByBox => (),
558 ExplicitSelf::ByRawPointer(_) => {
559 feature_gate::feature_err(
560 &fcx.tcx.sess.parse_sess,
561 "arbitrary_self_types",
564 "raw pointer `self` is unstable")
565 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
569 ExplicitSelf::Other => {
570 feature_gate::feature_err(
571 &fcx.tcx.sess.parse_sess,
572 "arbitrary_self_types",
574 GateIssue::Language,"arbitrary `self` types are unstable")
575 .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`")
582 fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
584 ast_generics: &hir::Generics)
586 let item_def_id = tcx.hir.local_def_id(item.id);
587 let ty = tcx.type_of(item_def_id);
588 if tcx.has_error_field(ty) {
592 let ty_predicates = tcx.predicates_of(item_def_id);
593 assert_eq!(ty_predicates.parent, None);
594 let variances = tcx.variances_of(item_def_id);
596 let mut constrained_parameters: FxHashSet<_> =
597 variances.iter().enumerate()
598 .filter(|&(_, &variance)| variance != ty::Bivariant)
599 .map(|(index, _)| Parameter(index as u32))
602 identify_constrained_type_params(tcx,
603 ty_predicates.predicates.as_slice(),
605 &mut constrained_parameters);
607 for (index, _) in variances.iter().enumerate() {
608 if constrained_parameters.contains(&Parameter(index as u32)) {
612 let (span, name) = match ast_generics.params[index] {
613 hir::GenericParam::Lifetime(ref ld) => (ld.lifetime.span, ld.lifetime.name.name()),
614 hir::GenericParam::Type(ref tp) => (tp.span, tp.name),
616 report_bivariance(tcx, span, name);
620 fn report_bivariance<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
622 param_name: ast::Name)
624 let mut err = error_392(tcx, span, param_name);
626 let suggested_marker_id = tcx.lang_items().phantom_data();
627 match suggested_marker_id {
630 &format!("consider removing `{}` or using a marker such as `{}`",
632 tcx.item_path_str(def_id)));
635 // no lang items, no help!
641 fn reject_shadowing_type_parameters(tcx: TyCtxt, def_id: DefId) {
642 let generics = tcx.generics_of(def_id);
643 let parent = tcx.generics_of(generics.parent.unwrap());
644 let impl_params: FxHashMap<_, _> = parent.types
646 .map(|tp| (tp.name, tp.def_id))
649 for method_param in &generics.types {
650 if impl_params.contains_key(&method_param.name) {
651 // Tighten up the span to focus on only the shadowing type
652 let type_span = tcx.def_span(method_param.def_id);
654 // The expectation here is that the original trait declaration is
655 // local so it should be okay to just unwrap everything.
656 let trait_def_id = impl_params[&method_param.name];
657 let trait_decl_span = tcx.def_span(trait_def_id);
658 error_194(tcx, type_span, trait_decl_span, &method_param.name.as_str()[..]);
663 pub struct CheckTypeWellFormedVisitor<'a, 'tcx: 'a> {
664 tcx: TyCtxt<'a, 'tcx, 'tcx>,
667 impl<'a, 'gcx> CheckTypeWellFormedVisitor<'a, 'gcx> {
668 pub fn new(tcx: TyCtxt<'a, 'gcx, 'gcx>)
669 -> CheckTypeWellFormedVisitor<'a, 'gcx> {
670 CheckTypeWellFormedVisitor {
676 impl<'a, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'a, 'tcx> {
677 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
678 NestedVisitorMap::None
681 fn visit_item(&mut self, i: &hir::Item) {
682 debug!("visit_item: {:?}", i);
683 let def_id = self.tcx.hir.local_def_id(i.id);
684 ty::maps::queries::check_item_well_formed::ensure(self.tcx, def_id);
685 intravisit::walk_item(self, i);
688 fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
689 debug!("visit_trait_item: {:?}", trait_item);
690 let def_id = self.tcx.hir.local_def_id(trait_item.id);
691 ty::maps::queries::check_trait_item_well_formed::ensure(self.tcx, def_id);
692 intravisit::walk_trait_item(self, trait_item)
695 fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
696 debug!("visit_impl_item: {:?}", impl_item);
697 let def_id = self.tcx.hir.local_def_id(impl_item.id);
698 ty::maps::queries::check_impl_item_well_formed::ensure(self.tcx, def_id);
699 intravisit::walk_impl_item(self, impl_item)
703 ///////////////////////////////////////////////////////////////////////////
706 struct AdtVariant<'tcx> {
707 fields: Vec<AdtField<'tcx>>,
710 struct AdtField<'tcx> {
715 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
716 fn non_enum_variant(&self, struct_def: &hir::VariantData) -> AdtVariant<'tcx> {
718 struct_def.fields().iter()
720 let field_ty = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
721 let field_ty = self.normalize_associated_types_in(field.span,
723 AdtField { ty: field_ty, span: field.span }
726 AdtVariant { fields: fields }
729 fn enum_variants(&self, enum_def: &hir::EnumDef) -> Vec<AdtVariant<'tcx>> {
730 enum_def.variants.iter()
731 .map(|variant| self.non_enum_variant(&variant.node.data))
735 fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
736 match self.tcx.impl_trait_ref(impl_def_id) {
737 Some(ref trait_ref) => {
738 // Trait impl: take implied bounds from all types that
739 // appear in the trait reference.
740 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
741 trait_ref.substs.types().collect()
745 // Inherent impl: take implied bounds from the self type.
746 let self_ty = self.tcx.type_of(impl_def_id);
747 let self_ty = self.normalize_associated_types_in(span, &self_ty);
754 fn error_392<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, param_name: ast::Name)
755 -> DiagnosticBuilder<'tcx> {
756 let mut err = struct_span_err!(tcx.sess, span, E0392,
757 "parameter `{}` is never used", param_name);
758 err.span_label(span, "unused type parameter");
762 fn error_194(tcx: TyCtxt, span: Span, trait_decl_span: Span, name: &str) {
763 struct_span_err!(tcx.sess, span, E0194,
764 "type parameter `{}` shadows another type parameter of the same name",
766 .span_label(span, "shadows another type parameter")
767 .span_label(trait_decl_span, format!("first `{}` declared here", name))