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