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