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, _, _, _, _) => {
34 match ty::impl_trait_ref(self.tcx, ast_util::local_def(item.id)) {
38 ast::Unsafety::Normal => { /* OK */ }
39 ast::Unsafety::Unsafe => {
40 self.tcx.sess.span_err(
42 "inherent impls cannot be declared as unsafe");
48 let trait_def = ty::lookup_trait_def(self.tcx, trait_ref.def_id());
49 match (trait_def.unsafety, unsafety) {
50 (ast::Unsafety::Normal, ast::Unsafety::Unsafe) => {
51 self.tcx.sess.span_err(
53 format!("implementing the trait `{}` is not unsafe",
54 trait_ref.user_string(self.tcx)).as_slice());
57 (ast::Unsafety::Unsafe, ast::Unsafety::Normal) => {
58 self.tcx.sess.span_err(
60 format!("the trait `{}` requires an `unsafe impl` declaration",
61 trait_ref.user_string(self.tcx)).as_slice());
64 (ast::Unsafety::Unsafe, ast::Unsafety::Unsafe) |
65 (ast::Unsafety::Normal, ast::Unsafety::Normal) => {
75 visit::walk_item(self, item);