]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/coherence/unsafety.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / librustc_typeck / coherence / unsafety.rs
1 //! Unsafety checker: every impl either implements a trait defined in this
2 //! crate or pertains to a type defined in this crate.
3
4 use rustc::ty::TyCtxt;
5 use rustc::hir::itemlikevisit::ItemLikeVisitor;
6 use rustc::hir::{self, Unsafety};
7
8 use rustc_error_codes::*;
9
10 pub fn check(tcx: TyCtxt<'_>) {
11 let mut unsafety = UnsafetyChecker { tcx };
12 tcx.hir().krate().visit_all_item_likes(&mut unsafety);
13 }
14
15 struct UnsafetyChecker<'tcx> {
16 tcx: TyCtxt<'tcx>,
17 }
18
19 impl UnsafetyChecker<'tcx> {
20 fn check_unsafety_coherence(&mut self,
21 item: &'v hir::Item,
22 impl_generics: Option<&hir::Generics>,
23 unsafety: hir::Unsafety,
24 polarity: hir::ImplPolarity)
25 {
26 let local_did = self.tcx.hir().local_def_id(item.hir_id);
27 if let Some(trait_ref) = self.tcx.impl_trait_ref(local_did) {
28 let trait_def = self.tcx.trait_def(trait_ref.def_id);
29 let unsafe_attr = impl_generics.and_then(|generics| {
30 generics.params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle")
31 });
32 match (trait_def.unsafety, unsafe_attr, unsafety, polarity) {
33 (Unsafety::Normal, None, Unsafety::Unsafe, hir::ImplPolarity::Positive) => {
34 span_err!(self.tcx.sess,
35 item.span,
36 E0199,
37 "implementing the trait `{}` is not unsafe",
38 trait_ref.print_only_trait_path());
39 }
40
41 (Unsafety::Unsafe, _, Unsafety::Normal, hir::ImplPolarity::Positive) => {
42 span_err!(self.tcx.sess,
43 item.span,
44 E0200,
45 "the trait `{}` requires an `unsafe impl` declaration",
46 trait_ref.print_only_trait_path());
47 }
48
49 (Unsafety::Normal, Some(attr_name), Unsafety::Normal,
50 hir::ImplPolarity::Positive) =>
51 {
52 span_err!(self.tcx.sess,
53 item.span,
54 E0569,
55 "requires an `unsafe impl` declaration due to `#[{}]` attribute",
56 attr_name);
57 }
58
59 (_, _, Unsafety::Unsafe, hir::ImplPolarity::Negative) => {
60 // Reported in AST validation
61 self.tcx.sess.delay_span_bug(item.span, "unsafe negative impl");
62 }
63 (_, _, Unsafety::Normal, hir::ImplPolarity::Negative) |
64 (Unsafety::Unsafe, _, Unsafety::Unsafe, hir::ImplPolarity::Positive) |
65 (Unsafety::Normal, Some(_), Unsafety::Unsafe, hir::ImplPolarity::Positive) |
66 (Unsafety::Normal, None, Unsafety::Normal, _) => {
67 // OK
68 }
69 }
70 }
71 }
72 }
73
74 impl ItemLikeVisitor<'v> for UnsafetyChecker<'tcx> {
75 fn visit_item(&mut self, item: &'v hir::Item) {
76 if let hir::ItemKind::Impl(unsafety, polarity, _, ref generics, ..) = item.kind {
77 self.check_unsafety_coherence(item, Some(generics), unsafety, polarity);
78 }
79 }
80
81 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
82 }
83
84 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
85 }
86 }