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 rustc_front::visit;
17 use rustc_front::hir::{Item, ItemImpl};
19 pub fn check(tcx: &ty::ctxt) {
20 let mut orphan = UnsafetyChecker { tcx: tcx };
21 visit::walk_crate(&mut orphan, tcx.map.krate());
24 struct UnsafetyChecker<'cx, 'tcx:'cx> {
25 tcx: &'cx ty::ctxt<'tcx>
28 impl<'cx, 'tcx, 'v> UnsafetyChecker<'cx, 'tcx> {
29 fn check_unsafety_coherence(&mut self, item: &'v hir::Item,
30 unsafety: hir::Unsafety,
31 polarity: hir::ImplPolarity) {
32 match self.tcx.impl_trait_ref(self.tcx.map.local_def_id(item.id)) {
36 hir::Unsafety::Normal => { /* OK */ }
37 hir::Unsafety::Unsafe => {
38 span_err!(self.tcx.sess, item.span, E0197,
39 "inherent impls cannot be declared as unsafe");
45 let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id);
46 match (trait_def.unsafety, unsafety, polarity) {
47 (hir::Unsafety::Unsafe,
48 hir::Unsafety::Unsafe, hir::ImplPolarity::Negative) => {
49 span_err!(self.tcx.sess, item.span, E0198,
50 "negative implementations are not unsafe");
53 (hir::Unsafety::Normal, hir::Unsafety::Unsafe, _) => {
54 span_err!(self.tcx.sess, item.span, E0199,
55 "implementing the trait `{}` is not unsafe",
59 (hir::Unsafety::Unsafe,
60 hir::Unsafety::Normal, hir::ImplPolarity::Positive) => {
61 span_err!(self.tcx.sess, item.span, E0200,
62 "the trait `{}` requires an `unsafe impl` declaration",
66 (hir::Unsafety::Unsafe,
67 hir::Unsafety::Normal, hir::ImplPolarity::Negative) |
68 (hir::Unsafety::Unsafe,
69 hir::Unsafety::Unsafe, hir::ImplPolarity::Positive) |
70 (hir::Unsafety::Normal, hir::Unsafety::Normal, _) => {
79 impl<'cx, 'tcx,'v> visit::Visitor<'v> for UnsafetyChecker<'cx, 'tcx> {
80 fn visit_item(&mut self, item: &'v hir::Item) {
82 hir::ItemDefaultImpl(unsafety, _) => {
83 self.check_unsafety_coherence(item, unsafety, hir::ImplPolarity::Positive);
85 hir::ItemImpl(unsafety, polarity, _, _, _, _) => {
86 self.check_unsafety_coherence(item, unsafety, polarity);
91 visit::walk_item(self, item);