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.
12 use check::{FnCtxt, Inherited, blank_fn_ctxt, regionck};
13 use constrained_type_params::{identify_constrained_type_params, Parameter};
15 use middle::def_id::DefId;
16 use middle::subst::{self, TypeSpace, FnSpace, ParamSpace, SelfSpace};
18 use middle::ty::{self, Ty};
19 use middle::ty::fold::{TypeFolder};
21 use std::cell::RefCell;
22 use std::collections::HashSet;
25 use syntax::codemap::{Span};
26 use syntax::parse::token::{special_idents};
27 use rustc_front::intravisit::{self, Visitor};
30 pub struct CheckTypeWellFormedVisitor<'ccx, 'tcx:'ccx> {
31 ccx: &'ccx CrateCtxt<'ccx, 'tcx>,
32 code: traits::ObligationCauseCode<'tcx>,
35 impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
36 pub fn new(ccx: &'ccx CrateCtxt<'ccx, 'tcx>)
37 -> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
38 CheckTypeWellFormedVisitor {
40 code: traits::ObligationCauseCode::RFC1214(
41 Rc::new(traits::ObligationCauseCode::MiscObligation))
45 fn tcx(&self) -> &ty::ctxt<'tcx> {
49 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
50 /// well-formed, meaning that they do not require any constraints not declared in the struct
51 /// definition itself. For example, this definition would be illegal:
53 /// struct Ref<'a, T> { x: &'a T }
55 /// because the type did not declare that `T:'a`.
57 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
58 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
60 fn check_item_well_formed(&mut self, item: &hir::Item) {
62 debug!("check_item_well_formed(it.id={}, it.name={})",
64 ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(item.id)));
67 /// Right now we check that every default trait implementation
68 /// has an implementation of itself. Basically, a case like:
70 /// `impl Trait for T {}`
72 /// has a requirement of `T: Trait` which was required for default
73 /// method implementations. Although this could be improved now that
74 /// there's a better infrastructure in place for this, it's being left
75 /// for a follow-up work.
77 /// Since there's such a requirement, we need to check *just* positive
78 /// implementations, otherwise things like:
80 /// impl !Send for T {}
82 /// won't be allowed unless there's an *explicit* implementation of `Send`
84 hir::ItemImpl(_, hir::ImplPolarity::Positive, _,
85 ref trait_ref, ref self_ty, _) => {
86 self.check_impl(item, self_ty, trait_ref);
88 hir::ItemImpl(_, hir::ImplPolarity::Negative, _, Some(_), _, _) => {
89 // FIXME(#27579) what amount of WF checking do we need for neg impls?
91 let trait_ref = ccx.tcx.impl_trait_ref(ccx.tcx.map.local_def_id(item.id)).unwrap();
92 ccx.tcx.populate_implementations_for_trait_if_necessary(trait_ref.def_id);
93 match ccx.tcx.lang_items.to_builtin_kind(trait_ref.def_id) {
94 Some(ty::BoundSend) | Some(ty::BoundSync) => {}
96 if !ccx.tcx.trait_has_default_impl(trait_ref.def_id) {
97 error_192(ccx, item.span);
102 hir::ItemFn(_, _, _, _, _, ref body) => {
103 self.check_item_fn(item, body);
105 hir::ItemStatic(..) => {
106 self.check_item_type(item);
108 hir::ItemConst(..) => {
109 self.check_item_type(item);
111 hir::ItemStruct(ref struct_def, ref ast_generics) => {
112 self.check_type_defn(item, |fcx| {
113 vec![struct_variant(fcx, struct_def)]
116 self.check_variances_for_type_defn(item, ast_generics);
118 hir::ItemEnum(ref enum_def, ref ast_generics) => {
119 self.check_type_defn(item, |fcx| {
120 enum_variants(fcx, enum_def)
123 self.check_variances_for_type_defn(item, ast_generics);
125 hir::ItemTrait(_, _, _, ref items) => {
126 self.check_trait(item, items);
132 fn check_trait_or_impl_item(&mut self, item_id: ast::NodeId, span: Span) {
133 let code = self.code.clone();
134 self.with_fcx(item_id, span, |fcx, this| {
135 let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
136 let free_id = fcx.inh.infcx.parameter_environment.free_id;
138 let item = fcx.tcx().impl_or_trait_item(fcx.tcx().map.local_def_id(item_id));
140 let mut implied_bounds = match item.container() {
141 ty::TraitContainer(_) => vec![],
142 ty::ImplContainer(def_id) => impl_implied_bounds(fcx, def_id, span)
146 ty::ConstTraitItem(assoc_const) => {
147 let ty = fcx.instantiate_type_scheme(span, free_substs, &assoc_const.ty);
148 fcx.register_wf_obligation(ty, span, code.clone());
150 ty::MethodTraitItem(method) => {
151 reject_shadowing_type_parameters(fcx.tcx(), span, &method.generics);
152 let method_ty = fcx.instantiate_type_scheme(span, free_substs, &method.fty);
153 let predicates = fcx.instantiate_bounds(span, free_substs, &method.predicates);
154 this.check_fn_or_method(fcx, span, &method_ty, &predicates,
155 free_id, &mut implied_bounds);
157 ty::TypeTraitItem(assoc_type) => {
158 if let Some(ref ty) = assoc_type.ty {
159 let ty = fcx.instantiate_type_scheme(span, free_substs, ty);
160 fcx.register_wf_obligation(ty, span, code.clone());
169 fn with_item_fcx<F>(&mut self, item: &hir::Item, f: F) where
170 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>,
171 &mut CheckTypeWellFormedVisitor<'ccx,'tcx>) -> Vec<Ty<'tcx>>,
173 self.with_fcx(item.id, item.span, f)
176 fn with_fcx<F>(&mut self, id: ast::NodeId, span: Span, mut f: F) where
177 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>,
178 &mut CheckTypeWellFormedVisitor<'ccx,'tcx>) -> Vec<Ty<'tcx>>,
181 let param_env = ty::ParameterEnvironment::for_item(ccx.tcx, id);
182 let tables = RefCell::new(ty::Tables::empty());
183 let inh = Inherited::new(ccx.tcx, &tables, param_env);
184 let fcx = blank_fn_ctxt(ccx, &inh, ty::FnDiverging, id);
185 let wf_tys = f(&fcx, self);
186 fcx.select_all_obligations_or_error();
187 regionck::regionck_item(&fcx, id, span, &wf_tys);
190 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
191 fn check_type_defn<F>(&mut self, item: &hir::Item, mut lookup_fields: F) where
192 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
194 self.with_item_fcx(item, |fcx, this| {
195 let variants = lookup_fields(fcx);
197 for variant in &variants {
198 // For DST, all intermediate types must be sized.
199 if let Some((_, fields)) = variant.fields.split_last() {
200 for field in fields {
201 fcx.register_builtin_bound(
204 traits::ObligationCause::new(field.span,
206 traits::FieldSized));
210 // All field types must be well-formed.
211 for field in &variant.fields {
212 fcx.register_wf_obligation(field.ty, field.span, this.code.clone())
216 let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
217 let predicates = fcx.tcx().lookup_predicates(fcx.tcx().map.local_def_id(item.id));
218 let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
219 this.check_where_clauses(fcx, item.span, &predicates);
221 vec![] // no implied bounds in a struct def'n
225 fn check_trait(&mut self,
227 items: &[hir::TraitItem])
229 let trait_def_id = self.tcx().map.local_def_id(item.id);
231 if self.ccx.tcx.trait_has_default_impl(trait_def_id) {
232 if !items.is_empty() {
233 error_380(self.ccx, item.span);
237 self.with_item_fcx(item, |fcx, this| {
238 let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
239 let predicates = fcx.tcx().lookup_predicates(trait_def_id);
240 let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
241 this.check_where_clauses(fcx, item.span, &predicates);
246 fn check_item_fn(&mut self,
250 self.with_item_fcx(item, |fcx, this| {
251 let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
252 let type_scheme = fcx.tcx().lookup_item_type(fcx.tcx().map.local_def_id(item.id));
253 let item_ty = fcx.instantiate_type_scheme(item.span, free_substs, &type_scheme.ty);
254 let bare_fn_ty = match item_ty.sty {
255 ty::TyBareFn(_, ref bare_fn_ty) => bare_fn_ty,
257 this.tcx().sess.span_bug(item.span, "Fn item without bare fn type");
261 let predicates = fcx.tcx().lookup_predicates(fcx.tcx().map.local_def_id(item.id));
262 let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
264 let mut implied_bounds = vec![];
265 this.check_fn_or_method(fcx, item.span, bare_fn_ty, &predicates,
266 body.id, &mut implied_bounds);
271 fn check_item_type(&mut self,
274 debug!("check_item_type: {:?}", item);
276 self.with_item_fcx(item, |fcx, this| {
277 let type_scheme = fcx.tcx().lookup_item_type(fcx.tcx().map.local_def_id(item.id));
278 let item_ty = fcx.instantiate_type_scheme(item.span,
281 .parameter_environment
285 fcx.register_wf_obligation(item_ty, item.span, this.code.clone());
287 vec![] // no implied bounds in a const etc
291 fn check_impl(&mut self,
293 ast_self_ty: &hir::Ty,
294 ast_trait_ref: &Option<hir::TraitRef>)
296 debug!("check_impl: {:?}", item);
298 self.with_item_fcx(item, |fcx, this| {
299 let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
300 let item_def_id = fcx.tcx().map.local_def_id(item.id);
302 match *ast_trait_ref {
303 Some(ref ast_trait_ref) => {
304 let trait_ref = fcx.tcx().impl_trait_ref(item_def_id).unwrap();
306 fcx.instantiate_type_scheme(
307 ast_trait_ref.path.span, free_substs, &trait_ref);
309 ty::wf::trait_obligations(fcx.infcx(),
312 ast_trait_ref.path.span,
314 for obligation in obligations {
315 fcx.register_predicate(obligation);
319 let self_ty = fcx.tcx().node_id_to_type(item.id);
320 let self_ty = fcx.instantiate_type_scheme(item.span, free_substs, &self_ty);
321 fcx.register_wf_obligation(self_ty, ast_self_ty.span, this.code.clone());
325 let predicates = fcx.tcx().lookup_predicates(item_def_id);
326 let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
327 this.check_where_clauses(fcx, item.span, &predicates);
329 impl_implied_bounds(fcx, fcx.tcx().map.local_def_id(item.id), item.span)
333 fn check_where_clauses<'fcx>(&mut self,
334 fcx: &FnCtxt<'fcx,'tcx>,
336 predicates: &ty::InstantiatedPredicates<'tcx>)
339 predicates.predicates
341 .flat_map(|p| ty::wf::predicate_obligations(fcx.infcx(),
347 for obligation in obligations {
348 fcx.register_predicate(obligation);
352 fn check_fn_or_method<'fcx>(&mut self,
353 fcx: &FnCtxt<'fcx,'tcx>,
355 fty: &ty::BareFnTy<'tcx>,
356 predicates: &ty::InstantiatedPredicates<'tcx>,
357 free_id: ast::NodeId,
358 implied_bounds: &mut Vec<Ty<'tcx>>)
360 let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
361 let fty = fcx.instantiate_type_scheme(span, free_substs, fty);
362 let free_id_outlive = fcx.tcx().region_maps.item_extent(free_id);
363 let sig = fcx.tcx().liberate_late_bound_regions(free_id_outlive, &fty.sig);
365 for &input_ty in &sig.inputs {
366 fcx.register_wf_obligation(input_ty, span, self.code.clone());
368 implied_bounds.extend(sig.inputs);
371 ty::FnConverging(output) => {
372 fcx.register_wf_obligation(output, span, self.code.clone());
374 // FIXME(#25759) return types should not be implied bounds
375 implied_bounds.push(output);
377 ty::FnDiverging => { }
380 self.check_where_clauses(fcx, span, predicates);
383 fn check_variances_for_type_defn(&self,
385 ast_generics: &hir::Generics)
387 let item_def_id = self.tcx().map.local_def_id(item.id);
388 let ty_predicates = self.tcx().lookup_predicates(item_def_id);
389 let variances = self.tcx().item_variances(item_def_id);
391 let mut constrained_parameters: HashSet<_> =
394 .filter(|&(_, _, &variance)| variance != ty::Bivariant)
395 .map(|(space, index, _)| self.param_ty(ast_generics, space, index))
396 .map(|p| Parameter::Type(p))
399 identify_constrained_type_params(self.tcx(),
400 ty_predicates.predicates.as_slice(),
402 &mut constrained_parameters);
404 for (space, index, _) in variances.types.iter_enumerated() {
405 let param_ty = self.param_ty(ast_generics, space, index);
406 if constrained_parameters.contains(&Parameter::Type(param_ty)) {
409 let span = self.ty_param_span(ast_generics, item, space, index);
410 self.report_bivariance(span, param_ty.name);
413 for (space, index, &variance) in variances.regions.iter_enumerated() {
414 if variance != ty::Bivariant {
418 assert_eq!(space, TypeSpace);
419 let span = ast_generics.lifetimes[index].lifetime.span;
420 let name = ast_generics.lifetimes[index].lifetime.name;
421 self.report_bivariance(span, name);
426 ast_generics: &hir::Generics,
431 let name = match space {
432 TypeSpace => ast_generics.ty_params[index].name,
433 SelfSpace => special_idents::type_self.name,
434 FnSpace => self.tcx().sess.bug("Fn space occupied?"),
437 ty::ParamTy { space: space, idx: index as u32, name: name }
440 fn ty_param_span(&self,
441 ast_generics: &hir::Generics,
448 TypeSpace => ast_generics.ty_params[index].span,
449 SelfSpace => item.span,
450 FnSpace => self.tcx().sess.span_bug(item.span, "Fn space occupied?"),
454 fn report_bivariance(&self,
456 param_name: ast::Name)
458 error_392(self.tcx(), span, param_name);
460 let suggested_marker_id = self.tcx().lang_items.phantom_data();
461 match suggested_marker_id {
463 self.tcx().sess.fileline_help(
465 &format!("consider removing `{}` or using a marker such as `{}`",
467 self.tcx().item_path_str(def_id)));
470 // no lang items, no help!
476 fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>,
478 generics: &ty::Generics<'tcx>) {
479 let impl_params = generics.types.get_slice(subst::TypeSpace).iter()
480 .map(|tp| tp.name).collect::<HashSet<_>>();
482 for method_param in generics.types.get_slice(subst::FnSpace) {
483 if impl_params.contains(&method_param.name) {
484 error_194(tcx, span, method_param.name);
489 impl<'ccx, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'ccx, 'tcx> {
490 fn visit_item(&mut self, i: &hir::Item) {
491 debug!("visit_item: {:?}", i);
492 self.check_item_well_formed(i);
493 intravisit::walk_item(self, i);
496 fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
497 debug!("visit_trait_item: {:?}", trait_item);
498 self.check_trait_or_impl_item(trait_item.id, trait_item.span);
499 intravisit::walk_trait_item(self, trait_item)
502 fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
503 debug!("visit_impl_item: {:?}", impl_item);
504 self.check_trait_or_impl_item(impl_item.id, impl_item.span);
505 intravisit::walk_impl_item(self, impl_item)
509 ///////////////////////////////////////////////////////////////////////////
512 struct AdtVariant<'tcx> {
513 fields: Vec<AdtField<'tcx>>,
516 struct AdtField<'tcx> {
521 fn struct_variant<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
522 struct_def: &hir::VariantData)
523 -> AdtVariant<'tcx> {
525 struct_def.fields().iter()
527 let field_ty = fcx.tcx().node_id_to_type(field.node.id);
528 let field_ty = fcx.instantiate_type_scheme(field.span,
531 .parameter_environment
534 AdtField { ty: field_ty, span: field.span }
537 AdtVariant { fields: fields }
540 fn enum_variants<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
541 enum_def: &hir::EnumDef)
542 -> Vec<AdtVariant<'tcx>> {
543 enum_def.variants.iter()
544 .map(|variant| struct_variant(fcx, &variant.node.data))
548 fn impl_implied_bounds<'fcx,'tcx>(fcx: &FnCtxt<'fcx, 'tcx>,
553 let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
554 match fcx.tcx().impl_trait_ref(impl_def_id) {
555 Some(ref trait_ref) => {
556 // Trait impl: take implied bounds from all types that
557 // appear in the trait reference.
558 let trait_ref = fcx.instantiate_type_scheme(span, free_substs, trait_ref);
559 trait_ref.substs.types.as_slice().to_vec()
563 // Inherent impl: take implied bounds from the self type.
564 let self_ty = fcx.tcx().lookup_item_type(impl_def_id).ty;
565 let self_ty = fcx.instantiate_type_scheme(span, free_substs, &self_ty);
571 pub fn error_192<'ccx,'tcx>(ccx: &'ccx CrateCtxt<'ccx, 'tcx>, span: Span) {
572 span_err!(ccx.tcx.sess, span, E0192,
573 "negative impls are only allowed for traits with \
574 default impls (e.g., `Send` and `Sync`)")
577 pub fn error_380<'ccx,'tcx>(ccx: &'ccx CrateCtxt<'ccx, 'tcx>, span: Span) {
578 span_err!(ccx.tcx.sess, span, E0380,
579 "traits with default impls (`e.g. unsafe impl \
580 Trait for ..`) must have no methods or associated items")
583 pub fn error_392<'tcx>(tcx: &ty::ctxt<'tcx>, span: Span, param_name: ast::Name) {
584 span_err!(tcx.sess, span, E0392,
585 "parameter `{}` is never used", param_name);
588 pub fn error_194<'tcx>(tcx: &ty::ctxt<'tcx>, span: Span, name: ast::Name) {
589 span_err!(tcx.sess, span, E0194,
590 "type parameter `{}` shadows another type parameter of the same name",