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