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 //! Unsafety checker: every impl either implements a trait defined in this
12 //! crate or pertains to a type defined in this crate.
14 use rustc::ty::TyCtxt;
15 use rustc::hir::itemlikevisit::ItemLikeVisitor;
16 use rustc::hir::{self, Unsafety};
18 pub fn check<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
19 let mut unsafety = UnsafetyChecker { tcx: tcx };
20 tcx.hir.krate().visit_all_item_likes(&mut unsafety);
23 struct UnsafetyChecker<'cx, 'tcx: 'cx> {
24 tcx: TyCtxt<'cx, 'tcx, 'tcx>,
27 impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> {
28 fn check_unsafety_coherence(&mut self,
30 impl_generics: Option<&hir::Generics>,
31 unsafety: hir::Unsafety,
32 polarity: hir::ImplPolarity) {
33 match self.tcx.impl_trait_ref(self.tcx.hir.local_def_id(item.id)) {
37 let trait_def = self.tcx.trait_def(trait_ref.def_id);
38 let unsafe_attr = impl_generics.and_then(|g| g.carries_unsafe_attr());
39 match (trait_def.unsafety, unsafe_attr, unsafety, polarity) {
40 (_, _, Unsafety::Unsafe, hir::ImplPolarity::Negative) => {
41 span_err!(self.tcx.sess,
44 "negative implementations are not unsafe");
47 (Unsafety::Normal, None, Unsafety::Unsafe, _) => {
48 span_err!(self.tcx.sess,
51 "implementing the trait `{}` is not unsafe",
55 (Unsafety::Unsafe, _, Unsafety::Normal, hir::ImplPolarity::Positive) => {
56 span_err!(self.tcx.sess,
59 "the trait `{}` requires an `unsafe impl` declaration",
63 (Unsafety::Normal, Some(g), Unsafety::Normal, hir::ImplPolarity::Positive) =>
65 span_err!(self.tcx.sess,
68 "requires an `unsafe impl` declaration due to `#[{}]` attribute",
72 (_, _, Unsafety::Normal, hir::ImplPolarity::Negative) |
73 (Unsafety::Unsafe, _, Unsafety::Unsafe, hir::ImplPolarity::Positive) |
74 (Unsafety::Normal, Some(_), Unsafety::Unsafe, hir::ImplPolarity::Positive) |
75 (Unsafety::Normal, None, Unsafety::Normal, _) => {
84 impl<'cx, 'tcx, 'v> ItemLikeVisitor<'v> for UnsafetyChecker<'cx, 'tcx> {
85 fn visit_item(&mut self, item: &'v hir::Item) {
87 hir::ItemDefaultImpl(unsafety, _) => {
88 self.check_unsafety_coherence(item, None, unsafety, hir::ImplPolarity::Positive);
90 hir::ItemImpl(unsafety, polarity, _, ref generics, ..) => {
91 self.check_unsafety_coherence(item, Some(generics), unsafety, polarity);
97 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
100 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {