]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/effect.rs
Auto merge of #31077 - nagisa:mir-temp-promotion, r=dotdash
[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::Def;
16 use middle::ty::{self, Ty};
17 use middle::ty::MethodCall;
18
19 use syntax::ast;
20 use syntax::codemap::Span;
21 use rustc_front::hir;
22 use rustc_front::intravisit;
23 use rustc_front::intravisit::{FnKind, Visitor};
24
25 #[derive(Copy, Clone)]
26 struct UnsafeContext {
27     push_unsafe_count: usize,
28     root: RootUnsafeContext,
29 }
30
31 impl UnsafeContext {
32     fn new(root: RootUnsafeContext) -> UnsafeContext {
33         UnsafeContext { root: root, push_unsafe_count: 0 }
34     }
35 }
36
37 #[derive(Copy, Clone, PartialEq)]
38 enum RootUnsafeContext {
39     SafeContext,
40     UnsafeFn,
41     UnsafeBlock(ast::NodeId),
42 }
43
44 fn type_is_unsafe_function(ty: Ty) -> bool {
45     match ty.sty {
46         ty::TyBareFn(_, ref f) => f.unsafety == hir::Unsafety::Unsafe,
47         _ => false,
48     }
49 }
50
51 struct EffectCheckVisitor<'a, 'tcx: 'a> {
52     tcx: &'a ty::ctxt<'tcx>,
53
54     /// Whether we're in an unsafe context.
55     unsafe_context: UnsafeContext,
56 }
57
58 impl<'a, 'tcx> EffectCheckVisitor<'a, 'tcx> {
59     fn require_unsafe(&mut self, span: Span, description: &str) {
60         if self.unsafe_context.push_unsafe_count > 0 { return; }
61         match self.unsafe_context.root {
62             SafeContext => {
63                 // Report an error.
64                 span_err!(self.tcx.sess, span, E0133,
65                           "{} requires unsafe function or block",
66                           description);
67             }
68             UnsafeBlock(block_id) => {
69                 // OK, but record this.
70                 debug!("effect: recording unsafe block as used: {}", block_id);
71                 self.tcx.used_unsafe.borrow_mut().insert(block_id);
72             }
73             UnsafeFn => {}
74         }
75     }
76 }
77
78 impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> {
79     fn visit_fn(&mut self, fn_kind: FnKind<'v>, fn_decl: &'v hir::FnDecl,
80                 block: &'v hir::Block, span: Span, _: ast::NodeId) {
81
82         let (is_item_fn, is_unsafe_fn) = match fn_kind {
83             FnKind::ItemFn(_, _, unsafety, _, _, _) =>
84                 (true, unsafety == hir::Unsafety::Unsafe),
85             FnKind::Method(_, sig, _) =>
86                 (true, sig.unsafety == hir::Unsafety::Unsafe),
87             _ => (false, false),
88         };
89
90         let old_unsafe_context = self.unsafe_context;
91         if is_unsafe_fn {
92             self.unsafe_context = UnsafeContext::new(UnsafeFn)
93         } else if is_item_fn {
94             self.unsafe_context = UnsafeContext::new(SafeContext)
95         }
96
97         intravisit::walk_fn(self, fn_kind, fn_decl, block, span);
98
99         self.unsafe_context = old_unsafe_context
100     }
101
102     fn visit_block(&mut self, block: &hir::Block) {
103         let old_unsafe_context = self.unsafe_context;
104         match block.rules {
105             hir::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 == hir::CompilerGenerated {
122                     self.unsafe_context.root = UnsafeBlock(block.id)
123                 }
124             }
125             hir::PushUnsafeBlock(..) => {
126                 self.unsafe_context.push_unsafe_count =
127                     self.unsafe_context.push_unsafe_count.checked_add(1).unwrap();
128             }
129             hir::PopUnsafeBlock(..) => {
130                 self.unsafe_context.push_unsafe_count =
131                     self.unsafe_context.push_unsafe_count.checked_sub(1).unwrap();
132             }
133             hir::DefaultBlock | hir::PushUnstableBlock | hir:: PopUnstableBlock => {}
134         }
135
136         intravisit::walk_block(self, block);
137
138         self.unsafe_context = old_unsafe_context
139     }
140
141     fn visit_expr(&mut self, expr: &hir::Expr) {
142         match expr.node {
143             hir::ExprMethodCall(_, _, _) => {
144                 let method_call = MethodCall::expr(expr.id);
145                 let base_type = self.tcx.tables.borrow().method_map[&method_call].ty;
146                 debug!("effect: method call case, base type is {:?}",
147                         base_type);
148                 if type_is_unsafe_function(base_type) {
149                     self.require_unsafe(expr.span,
150                                         "invocation of unsafe method")
151                 }
152             }
153             hir::ExprCall(ref base, _) => {
154                 let base_type = self.tcx.expr_ty_adjusted(base);
155                 debug!("effect: call case, base type is {:?}",
156                         base_type);
157                 if type_is_unsafe_function(base_type) {
158                     self.require_unsafe(expr.span, "call to unsafe function")
159                 }
160             }
161             hir::ExprUnary(hir::UnDeref, ref base) => {
162                 let base_type = self.tcx.expr_ty_adjusted(base);
163                 debug!("effect: unary case, base type is {:?}",
164                         base_type);
165                 if let ty::TyRawPtr(_) = base_type.sty {
166                     self.require_unsafe(expr.span, "dereference of raw pointer")
167                 }
168             }
169             hir::ExprInlineAsm(..) => {
170                 self.require_unsafe(expr.span, "use of inline assembly");
171             }
172             hir::ExprPath(..) => {
173                 if let Def::Static(_, true) = self.tcx.resolve_expr(expr) {
174                     self.require_unsafe(expr.span, "use of mutable static");
175                 }
176             }
177             _ => {}
178         }
179
180         intravisit::walk_expr(self, expr);
181     }
182 }
183
184 pub fn check_crate(tcx: &ty::ctxt) {
185     let mut visitor = EffectCheckVisitor {
186         tcx: tcx,
187         unsafe_context: UnsafeContext::new(SafeContext),
188     };
189
190     tcx.map.krate().visit_all_items(&mut visitor);
191 }