]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/effect.rs
Auto merge of #43766 - michaelwoerister:trans-scheduler-touch-up, r=alexcrichton
[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 ty::{self, TyCtxt};
16 use lint;
17
18 use syntax::ast;
19 use syntax_pos::Span;
20 use hir::{self, PatKind};
21 use hir::def::Def;
22 use hir::intravisit::{self, FnKind, Visitor, NestedVisitorMap};
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 struct EffectCheckVisitor<'a, 'tcx: 'a> {
44     tcx: TyCtxt<'a, 'tcx, 'tcx>,
45     tables: &'a ty::TypeckTables<'tcx>,
46     body_id: hir::BodyId,
47
48     /// Whether we're in an unsafe context.
49     unsafe_context: UnsafeContext,
50 }
51
52 impl<'a, 'tcx> EffectCheckVisitor<'a, 'tcx> {
53     fn require_unsafe_ext(&mut self, node_id: ast::NodeId, span: Span,
54                           description: &str, is_lint: bool) {
55         if self.unsafe_context.push_unsafe_count > 0 { return; }
56         match self.unsafe_context.root {
57             SafeContext => {
58                 if is_lint {
59                     self.tcx.lint_node(lint::builtin::SAFE_EXTERN_STATICS,
60                                        node_id,
61                                        span,
62                                        &format!("{} requires unsafe function or \
63                                                  block (error E0133)", description));
64                 } else {
65                     // Report an error.
66                     struct_span_err!(
67                         self.tcx.sess, span, E0133,
68                         "{} requires unsafe function or block", description)
69                         .span_label(span, description)
70                         .emit();
71                 }
72             }
73             UnsafeBlock(block_id) => {
74                 // OK, but record this.
75                 debug!("effect: recording unsafe block as used: {}", block_id);
76                 self.tcx.used_unsafe.borrow_mut().insert(block_id);
77             }
78             UnsafeFn => {}
79         }
80     }
81
82     fn require_unsafe(&mut self, span: Span, description: &str) {
83         self.require_unsafe_ext(ast::DUMMY_NODE_ID, span, description, false)
84     }
85 }
86
87 impl<'a, 'tcx> Visitor<'tcx> for EffectCheckVisitor<'a, 'tcx> {
88     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
89         NestedVisitorMap::None
90     }
91
92     fn visit_nested_body(&mut self, body: hir::BodyId) {
93         let old_tables = self.tables;
94         let old_body_id = self.body_id;
95         self.tables = self.tcx.body_tables(body);
96         self.body_id = body;
97         let body = self.tcx.hir.body(body);
98         self.visit_body(body);
99         self.tables = old_tables;
100         self.body_id = old_body_id;
101     }
102
103     fn visit_fn(&mut self, fn_kind: FnKind<'tcx>, fn_decl: &'tcx hir::FnDecl,
104                 body_id: hir::BodyId, span: Span, id: ast::NodeId) {
105
106         let (is_item_fn, is_unsafe_fn) = match fn_kind {
107             FnKind::ItemFn(_, _, unsafety, ..) =>
108                 (true, unsafety == hir::Unsafety::Unsafe),
109             FnKind::Method(_, sig, ..) =>
110                 (true, sig.unsafety == hir::Unsafety::Unsafe),
111             _ => (false, false),
112         };
113
114         let old_unsafe_context = self.unsafe_context;
115         if is_unsafe_fn {
116             self.unsafe_context = UnsafeContext::new(UnsafeFn)
117         } else if is_item_fn {
118             self.unsafe_context = UnsafeContext::new(SafeContext)
119         }
120
121         intravisit::walk_fn(self, fn_kind, fn_decl, body_id, span, id);
122
123         self.unsafe_context = old_unsafe_context
124     }
125
126     fn visit_block(&mut self, block: &'tcx hir::Block) {
127         let old_unsafe_context = self.unsafe_context;
128         match block.rules {
129             hir::UnsafeBlock(source) => {
130                 // By default only the outermost `unsafe` block is
131                 // "used" and so nested unsafe blocks are pointless
132                 // (the inner ones are unnecessary and we actually
133                 // warn about them). As such, there are two cases when
134                 // we need to create a new context, when we're
135                 // - outside `unsafe` and found a `unsafe` block
136                 //   (normal case)
137                 // - inside `unsafe`, found an `unsafe` block
138                 //   created internally to the compiler
139                 //
140                 // The second case is necessary to ensure that the
141                 // compiler `unsafe` blocks don't accidentally "use"
142                 // external blocks (e.g. `unsafe { println("") }`,
143                 // expands to `unsafe { ... unsafe { ... } }` where
144                 // the inner one is compiler generated).
145                 if self.unsafe_context.root == SafeContext || source == hir::CompilerGenerated {
146                     self.unsafe_context.root = UnsafeBlock(block.id)
147                 }
148             }
149             hir::PushUnsafeBlock(..) => {
150                 self.unsafe_context.push_unsafe_count =
151                     self.unsafe_context.push_unsafe_count.checked_add(1).unwrap();
152             }
153             hir::PopUnsafeBlock(..) => {
154                 self.unsafe_context.push_unsafe_count =
155                     self.unsafe_context.push_unsafe_count.checked_sub(1).unwrap();
156             }
157             hir::DefaultBlock => {}
158         }
159
160         intravisit::walk_block(self, block);
161
162         self.unsafe_context = old_unsafe_context
163     }
164
165     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
166         match expr.node {
167             hir::ExprMethodCall(..) => {
168                 let def_id = self.tables.type_dependent_defs[&expr.id].def_id();
169                 let sig = self.tcx.fn_sig(def_id);
170                 debug!("effect: method call case, signature is {:?}",
171                         sig);
172
173                 if sig.0.unsafety == hir::Unsafety::Unsafe {
174                     self.require_unsafe(expr.span,
175                                         "invocation of unsafe method")
176                 }
177             }
178             hir::ExprCall(ref base, _) => {
179                 let base_type = self.tables.expr_ty_adjusted(base);
180                 debug!("effect: call case, base type is {:?}",
181                         base_type);
182                 match base_type.sty {
183                     ty::TyFnDef(..) | ty::TyFnPtr(_) => {
184                         if base_type.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
185                             self.require_unsafe(expr.span, "call to unsafe function")
186                         }
187                     }
188                     _ => {}
189                 }
190             }
191             hir::ExprUnary(hir::UnDeref, ref base) => {
192                 let base_type = self.tables.expr_ty_adjusted(base);
193                 debug!("effect: unary case, base type is {:?}",
194                         base_type);
195                 if let ty::TyRawPtr(_) = base_type.sty {
196                     self.require_unsafe(expr.span, "dereference of raw pointer")
197                 }
198             }
199             hir::ExprInlineAsm(..) => {
200                 self.require_unsafe(expr.span, "use of inline assembly");
201             }
202             hir::ExprPath(hir::QPath::Resolved(_, ref path)) => {
203                 if let Def::Static(def_id, mutbl) = path.def {
204                     if mutbl {
205                         self.require_unsafe(expr.span, "use of mutable static");
206                     } else if match self.tcx.hir.get_if_local(def_id) {
207                         Some(hir::map::NodeForeignItem(..)) => true,
208                         Some(..) => false,
209                         None => self.tcx.is_foreign_item(def_id),
210                     } {
211                         self.require_unsafe_ext(expr.id, expr.span, "use of extern static", true);
212                     }
213                 }
214             }
215             hir::ExprField(ref base_expr, field) => {
216                 if let ty::TyAdt(adt, ..) = self.tables.expr_ty_adjusted(base_expr).sty {
217                     if adt.is_union() {
218                         self.require_unsafe(field.span, "access to union field");
219                     }
220                 }
221             }
222             hir::ExprAssign(ref lhs, ref rhs) => {
223                 if let hir::ExprField(ref base_expr, field) = lhs.node {
224                     if let ty::TyAdt(adt, ..) = self.tables.expr_ty_adjusted(base_expr).sty {
225                         if adt.is_union() {
226                             let field_ty = self.tables.expr_ty_adjusted(lhs);
227                             let owner_def_id = self.tcx.hir.body_owner_def_id(self.body_id);
228                             let param_env = self.tcx.param_env(owner_def_id);
229                             if field_ty.moves_by_default(self.tcx, param_env, field.span) {
230                                 self.require_unsafe(field.span,
231                                                     "assignment to non-`Copy` union field");
232                             }
233                             // Do not walk the field expr again.
234                             intravisit::walk_expr(self, base_expr);
235                             intravisit::walk_expr(self, rhs);
236                             return
237                         }
238                     }
239                 }
240             }
241             _ => {}
242         }
243
244         intravisit::walk_expr(self, expr);
245     }
246
247     fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
248         if let PatKind::Struct(_, ref fields, _) = pat.node {
249             if let ty::TyAdt(adt, ..) = self.tables.pat_ty(pat).sty {
250                 if adt.is_union() {
251                     for field in fields {
252                         self.require_unsafe(field.span, "matching on union field");
253                     }
254                 }
255             }
256         }
257
258         intravisit::walk_pat(self, pat);
259     }
260 }
261
262 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
263     let mut visitor = EffectCheckVisitor {
264         tcx,
265         tables: &ty::TypeckTables::empty(),
266         body_id: hir::BodyId { node_id: ast::CRATE_NODE_ID },
267         unsafe_context: UnsafeContext::new(SafeContext),
268     };
269
270     tcx.hir.krate().visit_all_item_likes(&mut visitor.as_deep_visitor());
271 }