]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/effect.rs
Update E0253.rs
[rust.git] / src / librustc / middle / effect.rs
1 // Copyright 2012-2013 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.
4 //
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.
10
11 //! Enforces the Rust effect system. Currently there is just one effect,
12 //! `unsafe`.
13 use self::RootUnsafeContext::*;
14
15 use dep_graph::DepNode;
16 use hir::def::Def;
17 use ty::{self, Ty, TyCtxt};
18 use ty::MethodCall;
19
20 use syntax::ast;
21 use syntax_pos::Span;
22 use hir;
23 use hir::intravisit;
24 use hir::intravisit::{FnKind, Visitor};
25
26 #[derive(Copy, Clone)]
27 struct UnsafeContext {
28     push_unsafe_count: usize,
29     root: RootUnsafeContext,
30 }
31
32 impl UnsafeContext {
33     fn new(root: RootUnsafeContext) -> UnsafeContext {
34         UnsafeContext { root: root, push_unsafe_count: 0 }
35     }
36 }
37
38 #[derive(Copy, Clone, PartialEq)]
39 enum RootUnsafeContext {
40     SafeContext,
41     UnsafeFn,
42     UnsafeBlock(ast::NodeId),
43 }
44
45 fn type_is_unsafe_function(ty: Ty) -> bool {
46     match ty.sty {
47         ty::TyFnDef(_, _, ref f) |
48         ty::TyFnPtr(ref f) => f.unsafety == hir::Unsafety::Unsafe,
49         _ => false,
50     }
51 }
52
53 struct EffectCheckVisitor<'a, 'tcx: 'a> {
54     tcx: TyCtxt<'a, 'tcx, 'tcx>,
55
56     /// Whether we're in an unsafe context.
57     unsafe_context: UnsafeContext,
58 }
59
60 impl<'a, 'tcx> EffectCheckVisitor<'a, 'tcx> {
61     fn require_unsafe(&mut self, span: Span, description: &str) {
62         if self.unsafe_context.push_unsafe_count > 0 { return; }
63         match self.unsafe_context.root {
64             SafeContext => {
65                 // Report an error.
66                 span_err!(self.tcx.sess, span, E0133,
67                           "{} requires unsafe function or block",
68                           description);
69             }
70             UnsafeBlock(block_id) => {
71                 // OK, but record this.
72                 debug!("effect: recording unsafe block as used: {}", block_id);
73                 self.tcx.used_unsafe.borrow_mut().insert(block_id);
74             }
75             UnsafeFn => {}
76         }
77     }
78 }
79
80 impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> {
81     fn visit_fn(&mut self, fn_kind: FnKind<'v>, fn_decl: &'v hir::FnDecl,
82                 block: &'v hir::Block, span: Span, id: ast::NodeId) {
83
84         let (is_item_fn, is_unsafe_fn) = match fn_kind {
85             FnKind::ItemFn(_, _, unsafety, _, _, _, _) =>
86                 (true, unsafety == hir::Unsafety::Unsafe),
87             FnKind::Method(_, sig, _, _) =>
88                 (true, sig.unsafety == hir::Unsafety::Unsafe),
89             _ => (false, false),
90         };
91
92         let old_unsafe_context = self.unsafe_context;
93         if is_unsafe_fn {
94             self.unsafe_context = UnsafeContext::new(UnsafeFn)
95         } else if is_item_fn {
96             self.unsafe_context = UnsafeContext::new(SafeContext)
97         }
98
99         intravisit::walk_fn(self, fn_kind, fn_decl, block, span, id);
100
101         self.unsafe_context = old_unsafe_context
102     }
103
104     fn visit_block(&mut self, block: &hir::Block) {
105         let old_unsafe_context = self.unsafe_context;
106         match block.rules {
107             hir::UnsafeBlock(source) => {
108                 // By default only the outermost `unsafe` block is
109                 // "used" and so nested unsafe blocks are pointless
110                 // (the inner ones are unnecessary and we actually
111                 // warn about them). As such, there are two cases when
112                 // we need to create a new context, when we're
113                 // - outside `unsafe` and found a `unsafe` block
114                 //   (normal case)
115                 // - inside `unsafe`, found an `unsafe` block
116                 //   created internally to the compiler
117                 //
118                 // The second case is necessary to ensure that the
119                 // compiler `unsafe` blocks don't accidentally "use"
120                 // external blocks (e.g. `unsafe { println("") }`,
121                 // expands to `unsafe { ... unsafe { ... } }` where
122                 // the inner one is compiler generated).
123                 if self.unsafe_context.root == SafeContext || source == hir::CompilerGenerated {
124                     self.unsafe_context.root = UnsafeBlock(block.id)
125                 }
126             }
127             hir::PushUnsafeBlock(..) => {
128                 self.unsafe_context.push_unsafe_count =
129                     self.unsafe_context.push_unsafe_count.checked_add(1).unwrap();
130             }
131             hir::PopUnsafeBlock(..) => {
132                 self.unsafe_context.push_unsafe_count =
133                     self.unsafe_context.push_unsafe_count.checked_sub(1).unwrap();
134             }
135             hir::DefaultBlock | hir::PushUnstableBlock | hir:: PopUnstableBlock => {}
136         }
137
138         intravisit::walk_block(self, block);
139
140         self.unsafe_context = old_unsafe_context
141     }
142
143     fn visit_expr(&mut self, expr: &hir::Expr) {
144         match expr.node {
145             hir::ExprMethodCall(_, _, _) => {
146                 let method_call = MethodCall::expr(expr.id);
147                 let base_type = self.tcx.tables.borrow().method_map[&method_call].ty;
148                 debug!("effect: method call case, base type is {:?}",
149                         base_type);
150                 if type_is_unsafe_function(base_type) {
151                     self.require_unsafe(expr.span,
152                                         "invocation of unsafe method")
153                 }
154             }
155             hir::ExprCall(ref base, _) => {
156                 let base_type = self.tcx.expr_ty_adjusted(base);
157                 debug!("effect: call case, base type is {:?}",
158                         base_type);
159                 if type_is_unsafe_function(base_type) {
160                     self.require_unsafe(expr.span, "call to unsafe function")
161                 }
162             }
163             hir::ExprUnary(hir::UnDeref, ref base) => {
164                 let base_type = self.tcx.expr_ty_adjusted(base);
165                 debug!("effect: unary case, base type is {:?}",
166                         base_type);
167                 if let ty::TyRawPtr(_) = base_type.sty {
168                     self.require_unsafe(expr.span, "dereference of raw pointer")
169                 }
170             }
171             hir::ExprInlineAsm(..) => {
172                 self.require_unsafe(expr.span, "use of inline assembly");
173             }
174             hir::ExprPath(..) => {
175                 if let Def::Static(_, true) = self.tcx.expect_def(expr.id) {
176                     self.require_unsafe(expr.span, "use of mutable static");
177                 }
178             }
179             _ => {}
180         }
181
182         intravisit::walk_expr(self, expr);
183     }
184 }
185
186 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
187     let _task = tcx.dep_graph.in_task(DepNode::EffectCheck);
188
189     let mut visitor = EffectCheckVisitor {
190         tcx: tcx,
191         unsafe_context: UnsafeContext::new(SafeContext),
192     };
193
194     tcx.map.krate().visit_all_items(&mut visitor);
195 }