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};
20 pub fn check(tcx: &ty::ctxt) {
21 let mut orphan = UnsafetyChecker { tcx: tcx };
22 visit::walk_crate(&mut orphan, tcx.map.krate());
25 struct UnsafetyChecker<'cx, 'tcx:'cx> {
26 tcx: &'cx ty::ctxt<'tcx>
29 impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> {
30 fn check_unsafety_coherence(&mut self, item: &'v ast::Item,
31 unsafety: ast::Unsafety,
32 polarity: ast::ImplPolarity) {
33 match self.tcx.impl_trait_ref(ast_util::local_def(item.id)) {
37 ast::Unsafety::Normal => { /* OK */ }
38 ast::Unsafety::Unsafe => {
39 span_err!(self.tcx.sess, item.span, E0197,
40 "inherent impls cannot be declared as unsafe");
46 let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id);
47 match (trait_def.unsafety, unsafety, polarity) {
48 (ast::Unsafety::Unsafe,
49 ast::Unsafety::Unsafe, ast::ImplPolarity::Negative) => {
50 span_err!(self.tcx.sess, item.span, E0198,
51 "negative implementations are not unsafe");
54 (ast::Unsafety::Normal, ast::Unsafety::Unsafe, _) => {
55 span_err!(self.tcx.sess, item.span, E0199,
56 "implementing the trait `{}` is not unsafe",
60 (ast::Unsafety::Unsafe,
61 ast::Unsafety::Normal, ast::ImplPolarity::Positive) => {
62 span_err!(self.tcx.sess, item.span, E0200,
63 "the trait `{}` requires an `unsafe impl` declaration",
67 (ast::Unsafety::Unsafe,
68 ast::Unsafety::Normal, ast::ImplPolarity::Negative) |
69 (ast::Unsafety::Unsafe,
70 ast::Unsafety::Unsafe, ast::ImplPolarity::Positive) |
71 (ast::Unsafety::Normal, ast::Unsafety::Normal, _) => {
80 impl<'cx, 'tcx,'v> visit::Visitor<'v> for UnsafetyChecker<'cx, 'tcx> {
81 fn visit_item(&mut self, item: &'v ast::Item) {
83 ast::ItemDefaultImpl(unsafety, _) => {
84 self.check_unsafety_coherence(item, unsafety, ast::ImplPolarity::Positive);
86 ast::ItemImpl(unsafety, polarity, _, _, _, _) => {
87 self.check_unsafety_coherence(item, unsafety, polarity);
92 visit::walk_item(self, item);