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.
15 use syntax::ast::{Item, ItemImpl};
19 use util::ppaux::UserString;
21 pub fn check(tcx: &ty::ctxt) {
22 let mut orphan = UnsafetyChecker { tcx: tcx };
23 visit::walk_crate(&mut orphan, tcx.map.krate());
26 struct UnsafetyChecker<'cx, 'tcx:'cx> {
27 tcx: &'cx ty::ctxt<'tcx>
30 impl<'cx, 'tcx,'v> visit::Visitor<'v> for UnsafetyChecker<'cx, 'tcx> {
31 fn visit_item(&mut self, item: &'v ast::Item) {
33 ast::ItemImpl(unsafety, polarity, _, _, _, _) => {
34 match ty::impl_trait_ref(self.tcx, ast_util::local_def(item.id)) {
38 ast::Unsafety::Normal => { /* OK */ }
39 ast::Unsafety::Unsafe => {
40 span_err!(self.tcx.sess, item.span, E0197,
41 "inherent impls cannot be declared as unsafe");
47 let trait_def = ty::lookup_trait_def(self.tcx, trait_ref.def_id);
48 match (trait_def.unsafety, unsafety, polarity) {
49 (ast::Unsafety::Unsafe,
50 ast::Unsafety::Unsafe, ast::ImplPolarity::Negative) => {
51 span_err!(self.tcx.sess, item.span, E0198,
52 "negative implementations are not unsafe");
55 (ast::Unsafety::Normal, ast::Unsafety::Unsafe, _) => {
56 span_err!(self.tcx.sess, item.span, E0199,
57 "implementing the trait `{}` is not unsafe",
58 trait_ref.user_string(self.tcx));
61 (ast::Unsafety::Unsafe,
62 ast::Unsafety::Normal, ast::ImplPolarity::Positive) => {
63 span_err!(self.tcx.sess, item.span, E0200,
64 "the trait `{}` requires an `unsafe impl` declaration",
65 trait_ref.user_string(self.tcx));
68 (ast::Unsafety::Unsafe,
69 ast::Unsafety::Normal, ast::ImplPolarity::Negative) |
70 (ast::Unsafety::Unsafe,
71 ast::Unsafety::Unsafe, ast::ImplPolarity::Positive) |
72 (ast::Unsafety::Normal, ast::Unsafety::Normal, _) => {
82 visit::walk_item(self, item);