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, wfcheck};
13 use constrained_type_params::{identify_constrained_type_params, Parameter};
16 use middle::subst::{self, TypeSpace, FnSpace, ParamSpace, SelfSpace};
18 use middle::ty::{self, Ty};
19 use middle::ty::fold::{TypeFolder, TypeFoldable, super_fold_ty};
21 use std::cell::RefCell;
22 use std::collections::HashSet;
24 use syntax::codemap::{DUMMY_SP, Span};
25 use syntax::parse::token::special_idents;
27 use rustc_front::intravisit::{self, Visitor, FnKind};
30 pub struct CheckTypeWellFormedVisitor<'ccx, 'tcx:'ccx> {
31 ccx: &'ccx CrateCtxt<'ccx, 'tcx>,
32 cache: HashSet<Ty<'tcx>>
35 impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
36 pub fn new(ccx: &'ccx CrateCtxt<'ccx, 'tcx>) -> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
37 CheckTypeWellFormedVisitor { ccx: ccx, cache: HashSet::new() }
40 fn tcx(&self) -> &ty::ctxt<'tcx> {
44 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
45 /// well-formed, meaning that they do not require any constraints not declared in the struct
46 /// definition itself. For example, this definition would be illegal:
48 /// struct Ref<'a, T> { x: &'a T }
50 /// because the type did not declare that `T:'a`.
52 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
53 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
55 fn check_item_well_formed(&mut self, item: &hir::Item) {
57 debug!("check_item_well_formed(it.id={}, it.name={})",
59 ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(item.id)));
62 /// Right now we check that every default trait implementation
63 /// has an implementation of itself. Basically, a case like:
65 /// `impl Trait for T {}`
67 /// has a requirement of `T: Trait` which was required for default
68 /// method implementations. Although this could be improved now that
69 /// there's a better infrastructure in place for this, it's being left
70 /// for a follow-up work.
72 /// Since there's such a requirement, we need to check *just* positive
73 /// implementations, otherwise things like:
75 /// impl !Send for T {}
77 /// won't be allowed unless there's an *explicit* implementation of `Send`
79 hir::ItemImpl(_, hir::ImplPolarity::Positive, _, _, _, _) => {
80 self.check_impl(item);
82 hir::ItemImpl(_, hir::ImplPolarity::Negative, _, Some(_), _, _) => {
83 let item_def_id = ccx.tcx.map.local_def_id(item.id);
84 let trait_ref = ccx.tcx.impl_trait_ref(item_def_id).unwrap();
85 ccx.tcx.populate_implementations_for_trait_if_necessary(trait_ref.def_id);
86 match ccx.tcx.lang_items.to_builtin_kind(trait_ref.def_id) {
87 Some(ty::BoundSend) | Some(ty::BoundSync) => {}
89 if !ccx.tcx.trait_has_default_impl(trait_ref.def_id) {
90 wfcheck::error_192(ccx, item.span);
96 self.check_item_type(item);
98 hir::ItemStatic(..) => {
99 self.check_item_type(item);
101 hir::ItemConst(..) => {
102 self.check_item_type(item);
104 hir::ItemStruct(ref struct_def, ref ast_generics) => {
105 self.check_type_defn(item, |fcx| {
106 vec![struct_variant(fcx, struct_def)]
109 self.check_variances_for_type_defn(item, ast_generics);
111 hir::ItemEnum(ref enum_def, ref ast_generics) => {
112 self.check_type_defn(item, |fcx| {
113 enum_variants(fcx, enum_def)
116 self.check_variances_for_type_defn(item, ast_generics);
118 hir::ItemTrait(_, _, _, ref items) => {
119 let trait_predicates =
120 ccx.tcx.lookup_predicates(ccx.tcx.map.local_def_id(item.id));
121 reject_non_type_param_bounds(ccx.tcx, item.span, &trait_predicates);
122 if ccx.tcx.trait_has_default_impl(ccx.tcx.map.local_def_id(item.id)) {
123 if !items.is_empty() {
124 wfcheck::error_380(ccx, item.span);
132 fn with_fcx<F>(&mut self, item: &hir::Item, mut f: F) where
133 F: for<'fcx> FnMut(&mut CheckTypeWellFormedVisitor<'ccx, 'tcx>, &FnCtxt<'fcx, 'tcx>),
136 let item_def_id = ccx.tcx.map.local_def_id(item.id);
137 let type_scheme = ccx.tcx.lookup_item_type(item_def_id);
138 let type_predicates = ccx.tcx.lookup_predicates(item_def_id);
139 reject_non_type_param_bounds(ccx.tcx, item.span, &type_predicates);
140 let free_id_outlive = ccx.tcx.region_maps.item_extent(item.id);
141 let param_env = ccx.tcx.construct_parameter_environment(item.span,
142 &type_scheme.generics,
145 let tables = RefCell::new(ty::Tables::empty());
146 let inh = Inherited::new(ccx.tcx, &tables, param_env);
147 let fcx = blank_fn_ctxt(ccx, &inh, ty::FnConverging(type_scheme.ty), item.id);
149 fcx.select_all_obligations_or_error();
150 regionck::regionck_item(&fcx, item.id, item.span, &[]);
153 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
154 fn check_type_defn<F>(&mut self, item: &hir::Item, mut lookup_fields: F) where
155 F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
157 self.with_fcx(item, |this, fcx| {
158 let variants = lookup_fields(fcx);
159 let mut bounds_checker = BoundsChecker::new(fcx,
161 Some(&mut this.cache));
162 debug!("check_type_defn at bounds_checker.scope: {:?}", bounds_checker.scope);
164 for variant in &variants {
165 for field in &variant.fields {
166 // Regions are checked below.
167 bounds_checker.check_traits_in_ty(field.ty, field.span);
170 // For DST, all intermediate types must be sized.
171 if let Some((_, fields)) = variant.fields.split_last() {
172 for field in fields {
173 fcx.register_builtin_bound(
176 traits::ObligationCause::new(field.span,
178 traits::FieldSized));
183 for field in variants.iter().flat_map(|v| v.fields.iter()) {
184 fcx.register_old_wf_obligation(field.ty, field.span, traits::MiscObligation);
189 fn check_item_type(&mut self,
192 self.with_fcx(item, |this, fcx| {
193 let mut bounds_checker = BoundsChecker::new(fcx,
195 Some(&mut this.cache));
196 debug!("check_item_type at bounds_checker.scope: {:?}", bounds_checker.scope);
198 let item_def_id = fcx.tcx().map.local_def_id(item.id);
199 let type_scheme = fcx.tcx().lookup_item_type(item_def_id);
200 let item_ty = fcx.instantiate_type_scheme(item.span,
203 .parameter_environment
207 bounds_checker.check_traits_in_ty(item_ty, item.span);
211 fn check_impl(&mut self,
214 self.with_fcx(item, |this, fcx| {
215 let mut bounds_checker = BoundsChecker::new(fcx,
217 Some(&mut this.cache));
218 debug!("check_impl at bounds_checker.scope: {:?}", bounds_checker.scope);
220 // Find the impl self type as seen from the "inside" --
221 // that is, with all type parameters converted from bound
223 let self_ty = fcx.tcx().node_id_to_type(item.id);
224 let self_ty = fcx.instantiate_type_scheme(item.span,
227 .parameter_environment
231 bounds_checker.check_traits_in_ty(self_ty, item.span);
233 // Similarly, obtain an "inside" reference to the trait
234 // that the impl implements.
235 let trait_ref = match fcx.tcx().impl_trait_ref(fcx.tcx().map.local_def_id(item.id)) {
240 let trait_ref = fcx.instantiate_type_scheme(item.span,
243 .parameter_environment
247 // We are stricter on the trait-ref in an impl than the
248 // self-type. In particular, we enforce region
249 // relationships. The reason for this is that (at least
250 // presently) "applying" an impl does not require that the
251 // application site check the well-formedness constraints on the
252 // trait reference. Instead, this is done at the impl site.
253 // Arguably this is wrong and we should treat the trait-reference
254 // the same way as we treat the self-type.
255 bounds_checker.check_trait_ref(&trait_ref, item.span);
258 traits::ObligationCause::new(
261 traits::ItemObligation(trait_ref.def_id));
263 // Find the supertrait bounds. This will add `int:Bar`.
264 let poly_trait_ref = ty::Binder(trait_ref);
265 let predicates = fcx.tcx().lookup_super_predicates(poly_trait_ref.def_id());
266 let predicates = predicates.instantiate_supertrait(fcx.tcx(), &poly_trait_ref);
268 let selcx = &mut traits::SelectionContext::new(fcx.infcx());
269 traits::normalize(selcx, cause.clone(), &predicates)
271 for predicate in predicates.value.predicates {
272 fcx.register_predicate(traits::Obligation::new(cause.clone(), predicate));
274 for obligation in predicates.obligations {
275 fcx.register_predicate(obligation);
280 fn check_variances_for_type_defn(&self,
282 ast_generics: &hir::Generics)
284 let item_def_id = self.tcx().map.local_def_id(item.id);
285 let ty_predicates = self.tcx().lookup_predicates(item_def_id);
286 let variances = self.tcx().item_variances(item_def_id);
288 let mut constrained_parameters: HashSet<_> =
291 .filter(|&(_, _, &variance)| variance != ty::Bivariant)
292 .map(|(space, index, _)| self.param_ty(ast_generics, space, index))
293 .map(|p| Parameter::Type(p))
296 identify_constrained_type_params(self.tcx(),
297 ty_predicates.predicates.as_slice(),
299 &mut constrained_parameters);
301 for (space, index, _) in variances.types.iter_enumerated() {
302 let param_ty = self.param_ty(ast_generics, space, index);
303 if constrained_parameters.contains(&Parameter::Type(param_ty)) {
306 let span = self.ty_param_span(ast_generics, item, space, index);
307 self.report_bivariance(span, param_ty.name);
310 for (space, index, &variance) in variances.regions.iter_enumerated() {
311 if variance != ty::Bivariant {
315 assert_eq!(space, TypeSpace);
316 let span = ast_generics.lifetimes[index].lifetime.span;
317 let name = ast_generics.lifetimes[index].lifetime.name;
318 self.report_bivariance(span, name);
323 ast_generics: &hir::Generics,
328 let name = match space {
329 TypeSpace => ast_generics.ty_params[index].name,
330 SelfSpace => special_idents::type_self.name,
331 FnSpace => self.tcx().sess.bug("Fn space occupied?"),
334 ty::ParamTy { space: space, idx: index as u32, name: name }
337 fn ty_param_span(&self,
338 ast_generics: &hir::Generics,
345 TypeSpace => ast_generics.ty_params[index].span,
346 SelfSpace => item.span,
347 FnSpace => self.tcx().sess.span_bug(item.span, "Fn space occupied?"),
351 fn report_bivariance(&self,
353 param_name: ast::Name)
355 wfcheck::error_392(self.tcx(), span, param_name);
357 let suggested_marker_id = self.tcx().lang_items.phantom_data();
358 match suggested_marker_id {
360 self.tcx().sess.fileline_help(
362 &format!("consider removing `{}` or using a marker such as `{}`",
364 self.tcx().item_path_str(def_id)));
367 // no lang items, no help!
373 // Reject any predicates that do not involve a type parameter.
374 fn reject_non_type_param_bounds<'tcx>(tcx: &ty::ctxt<'tcx>,
376 predicates: &ty::GenericPredicates<'tcx>) {
377 for predicate in &predicates.predicates {
379 &ty::Predicate::Trait(ty::Binder(ref tr)) => {
380 let found_param = tr.input_types().iter()
381 .flat_map(|ty| ty.walk())
383 if !found_param { report_bound_error(tcx, span, tr.self_ty() )}
385 &ty::Predicate::TypeOutlives(ty::Binder(ty::OutlivesPredicate(ty, _))) => {
386 let found_param = ty.walk().any(|t| is_ty_param(t));
387 if !found_param { report_bound_error(tcx, span, ty) }
393 fn report_bound_error<'t>(tcx: &ty::ctxt<'t>,
395 bounded_ty: ty::Ty<'t>) {
396 span_err!(tcx.sess, span, E0193,
397 "cannot bound type `{}`, where clause \
398 bounds may only be attached to types involving \
403 fn is_ty_param(ty: ty::Ty) -> bool {
405 &ty::TyParam(_) => true,
411 fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>,
413 generics: &ty::Generics<'tcx>) {
414 let impl_params = generics.types.get_slice(subst::TypeSpace).iter()
415 .map(|tp| tp.name).collect::<HashSet<_>>();
417 for method_param in generics.types.get_slice(subst::FnSpace) {
418 if impl_params.contains(&method_param.name) {
419 wfcheck::error_194(tcx, span, method_param.name);
424 impl<'ccx, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'ccx, 'tcx> {
425 fn visit_item(&mut self, i: &hir::Item) {
426 self.check_item_well_formed(i);
427 intravisit::walk_item(self, i);
430 fn visit_fn(&mut self,
431 fk: FnKind<'v>, fd: &'v hir::FnDecl,
432 b: &'v hir::Block, span: Span, id: ast::NodeId) {
434 FnKind::Closure | FnKind::ItemFn(..) => {}
435 FnKind::Method(..) => {
436 match self.tcx().impl_or_trait_item(self.tcx().map.local_def_id(id)) {
437 ty::ImplOrTraitItem::MethodTraitItem(ty_method) => {
438 reject_shadowing_type_parameters(self.tcx(), span, &ty_method.generics)
444 intravisit::walk_fn(self, fk, fd, b, span)
447 fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
448 if let hir::MethodTraitItem(_, None) = trait_item.node {
449 match self.tcx().impl_or_trait_item(self.tcx().map.local_def_id(trait_item.id)) {
450 ty::ImplOrTraitItem::MethodTraitItem(ty_method) => {
451 reject_non_type_param_bounds(
454 &ty_method.predicates);
455 reject_shadowing_type_parameters(
458 &ty_method.generics);
464 intravisit::walk_trait_item(self, trait_item)
468 pub struct BoundsChecker<'cx,'tcx:'cx> {
469 fcx: &'cx FnCtxt<'cx,'tcx>,
472 scope: region::CodeExtent,
474 binding_count: usize,
475 cache: Option<&'cx mut HashSet<Ty<'tcx>>>,
478 impl<'cx,'tcx> BoundsChecker<'cx,'tcx> {
479 pub fn new(fcx: &'cx FnCtxt<'cx,'tcx>,
481 cache: Option<&'cx mut HashSet<Ty<'tcx>>>)
482 -> BoundsChecker<'cx,'tcx> {
483 let scope = fcx.tcx().region_maps.item_extent(scope);
484 BoundsChecker { fcx: fcx, span: DUMMY_SP, scope: scope,
485 cache: cache, binding_count: 0 }
488 /// Given a trait ref like `A : Trait<B>`, where `Trait` is defined as (say):
490 /// trait Trait<B:OtherTrait> : Copy { ... }
492 /// This routine will check that `B : OtherTrait` and `A : Trait<B>`. It will also recursively
493 /// check that the types `A` and `B` are well-formed.
495 /// Note that it does not (currently, at least) check that `A : Copy` (that check is delegated
496 /// to the point where impl `A : Trait<B>` is implemented).
497 pub fn check_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, span: Span) {
498 let trait_predicates = self.fcx.tcx().lookup_predicates(trait_ref.def_id);
500 let bounds = self.fcx.instantiate_bounds(span,
504 self.fcx.add_obligations_for_parameters(
505 traits::ObligationCause::new(
508 traits::ItemObligation(trait_ref.def_id)),
511 for &ty in &trait_ref.substs.types {
512 self.check_traits_in_ty(ty, span);
516 fn check_traits_in_ty(&mut self, ty: Ty<'tcx>, span: Span) {
518 // When checking types outside of a type def'n, we ignore
519 // region obligations. See discussion below in fold_ty().
520 self.binding_count += 1;
522 self.binding_count -= 1;
526 impl<'cx,'tcx> TypeFolder<'tcx> for BoundsChecker<'cx,'tcx> {
527 fn tcx(&self) -> &ty::ctxt<'tcx> {
531 fn fold_binder<T>(&mut self, binder: &ty::Binder<T>) -> ty::Binder<T>
532 where T : TypeFoldable<'tcx>
534 self.binding_count += 1;
535 let value = self.fcx.tcx().liberate_late_bound_regions(
538 debug!("BoundsChecker::fold_binder: late-bound regions replaced: {:?} at scope: {:?}",
540 let value = value.fold_with(self);
541 self.binding_count -= 1;
545 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
546 debug!("BoundsChecker t={:?}",
550 Some(ref mut cache) => {
551 if !cache.insert(t) {
552 // Already checked this type! Don't check again.
561 ty::TyStruct(def, substs) |
562 ty::TyEnum(def, substs) => {
563 let type_predicates = def.predicates(self.fcx.tcx());
564 let bounds = self.fcx.instantiate_bounds(self.span, substs,
567 if self.binding_count == 0 {
568 self.fcx.add_obligations_for_parameters(
569 traits::ObligationCause::new(self.span,
571 traits::ItemObligation(def.did)),
574 // There are two circumstances in which we ignore
575 // region obligations.
577 // The first is when we are inside of a closure
578 // type. This is because in that case the region
579 // obligations for the parameter types are things
580 // that the closure body gets to assume and the
581 // caller must prove at the time of call. In other
582 // words, if there is a type like `<'a, 'b> | &'a
583 // &'b int |`, it is well-formed, and caller will
584 // have to show that `'b : 'a` at the time of
587 // The second is when we are checking for
588 // well-formedness outside of a type def'n or fn
589 // body. This is for a similar reason: in general,
590 // we only do WF checking for regions in the
591 // result of expressions and type definitions, so
592 // to as allow for implicit where clauses.
594 // (I believe we should do the same for traits, but
595 // that will require an RFC. -nmatsakis)
596 let bounds = filter_to_trait_obligations(bounds);
597 self.fcx.add_obligations_for_parameters(
598 traits::ObligationCause::new(self.span,
600 traits::ItemObligation(def.did)),
604 self.fold_substs(substs);
607 super_fold_ty(self, t);
611 t // we're not folding to produce a new type, so just return `t` here
615 ///////////////////////////////////////////////////////////////////////////
618 struct AdtVariant<'tcx> {
619 fields: Vec<AdtField<'tcx>>,
622 struct AdtField<'tcx> {
627 fn struct_variant<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
628 struct_def: &hir::VariantData)
629 -> AdtVariant<'tcx> {
631 struct_def.fields().iter()
633 let field_ty = fcx.tcx().node_id_to_type(field.node.id);
634 let field_ty = fcx.instantiate_type_scheme(field.span,
637 .parameter_environment
640 AdtField { ty: field_ty, span: field.span }
643 AdtVariant { fields: fields }
646 fn enum_variants<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
647 enum_def: &hir::EnumDef)
648 -> Vec<AdtVariant<'tcx>> {
649 enum_def.variants.iter()
650 .map(|variant| struct_variant(fcx, &variant.node.data))
654 fn filter_to_trait_obligations<'tcx>(bounds: ty::InstantiatedPredicates<'tcx>)
655 -> ty::InstantiatedPredicates<'tcx>
657 let mut result = ty::InstantiatedPredicates::empty();
658 for (space, _, predicate) in bounds.predicates.iter_enumerated() {
660 ty::Predicate::Trait(..) |
661 ty::Predicate::Projection(..) => {
662 result.predicates.push(space, predicate.clone())
664 ty::Predicate::WellFormed(..) |
665 ty::Predicate::ObjectSafe(..) |
666 ty::Predicate::Equate(..) |
667 ty::Predicate::TypeOutlives(..) |
668 ty::Predicate::RegionOutlives(..) => {