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